Skip to content

Instantly share code, notes, and snippets.

@geordee
Created July 23, 2017 07:00
Show Gist options
  • Save geordee/22d60c75486ba9afee34988713295628 to your computer and use it in GitHub Desktop.
Save geordee/22d60c75486ba9afee34988713295628 to your computer and use it in GitHub Desktop.
Pivot a table using Python/Pandas
#!/usr/bin/env python
import os
import numpy
import pandas
xlsx = './workbook.xlsx'
df = pandas.read_excel(open(xlsx,'rb'), sheetname=1)
df2 = pandas.pivot_table(df,
values='Sales',
index=['Department', 'Category', 'Item'],
columns=['Store'],
aggfunc=numpy.sum)
parts = os.path.splitext(xlsx)
oxlsx = parts[0] + '_pivoted' + parts[1]
writer = pandas.ExcelWriter(oxlsx)
df2.to_excel(writer, sheet_name='Sheet1', merge_cells=False)
writer.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment