Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to drop double header resulting from pivot in Pandas?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading