Skip to content

Instantly share code, notes, and snippets.

@gdalmau
Forked from ecarreras/pivotpandas.py
Last active May 2, 2018 13:01
Show Gist options
  • Save gdalmau/1f2592e3b54fc66167ad40b504c8ab83 to your computer and use it in GitHub Desktop.
Save gdalmau/1f2592e3b54fc66167ad40b504c8ab83 to your computer and use it in GitHub Desktop.
Pandas pivot table
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Create DataFrame from Excel
df = pd.read_excel('/home/ecarreras/Desktop/l.xls')
# Create pivot table from DataFrame
table = pd.pivot_table(
df, index=['empresa', 'producto'], values=['price_subtotal'], aggfunc=[np.sum], fill_value=0
)
# Group pivot table by column specified
table_tots = table.groupby(level='empresa').sum()
# ?
table_tots.index = [table_tots.index, ['Total'] * len(table_tots)]
# Add total to the last row
result = pd.concat([table, table_tots]).sort_index().append(table.sum().rename(('Total empresas', '')))
result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment