Problem
I've done a pivot table in pandas, but I end up with a double header when I export to csv.
import pandas as pd
df = pd.DataFrame({'Year': [1, 2, 3, 4, 1, 2, 3, 4],
'Product': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
'net_sales': [55, 40, 84, 31, 56, 78, 34, 12]})
pvt_df = pd.pivot_table(df, values=['net_sales'], index=['Year'], columns=['Product'])
pvt_df.to_csv('sales.csv')
Which looks like below:
net_sales net_sales
Product A B
Year
1 55 56
2 40 78
3 84 34
4 31 12
Desired Result
What can I do to make the CSV export look like below?
Year A B
1 55 56
2 40 78
3 84 34
4 31 12
CodePudding user response:
You can try
pvt_df = pd.pivot_table(df, values='net_sales', index='Year', columns='Product').reset_index()
pvt_df.to_csv('sales.csv',index=False)
CodePudding user response:
Use pandas.DataFrame.droplevel
with axis=1
to drop a level from the columns:
>>> pvt_df.droplevel(0, axis=1)
Product A B
Year
1 55 56
2 40 78
3 84 34
4 31 12
>>> pvt_df.droplevel(0, axis=1).rename_axis(None, axis=1)
A B
Year
1 55 56
2 40 78
3 84 34
4 31 12
>>> pvt_df.droplevel(0, axis=1).rename_axis(None, axis=1).reset_index()
Year A B
0 1 55 56
1 2 40 78
2 3 84 34
3 4 31 12