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
>Solution :
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)