Skip to content

Instantly share code, notes, and snippets.

@geordee
Created July 23, 2017 06:59
Show Gist options
  • Save geordee/70c595804b08c4cbdb3b44dcd622a20e to your computer and use it in GitHub Desktop.
Save geordee/70c595804b08c4cbdb3b44dcd622a20e to your computer and use it in GitHub Desktop.
Unpivot 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=0)
id_vars = ['Department', 'Category', 'Item']
value_vars = [item for item in list(df.columns.values) if item not in list(id_vars)]
df2 = pandas.melt(df,
id_vars=id_vars,
value_vars=value_vars,
var_name=['Store'],
value_name='Sales')
parts = os.path.splitext(xlsx)
oxlsx = parts[0] + '_unpivoted' + parts[1]
writer = pandas.ExcelWriter(oxlsx)
df2.to_excel(writer, sheet_name='Sheet1', index=False)
writer.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment