Created
July 23, 2017 06:59
-
-
Save geordee/70c595804b08c4cbdb3b44dcd622a20e to your computer and use it in GitHub Desktop.
Unpivot a table using Python/Pandas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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