1

Sample Data frame :

import pandas as pd
idx = pd.MultiIndex.from_product([['Microsoft', 'Google', 'Apple'],
                                  ['OS', 'Web']],
                                 names=['Brand', 'Metric'])
col = ['Count']

df = pd.DataFrame(10, idx, col)
df

the data looks like this

enter image description here

When I download it as csv then it download like

df.to_csv('example.csv')

enter image description here

My Requirement is to download this data as pivot table, I am not able to find any way to move the second index as column name, the desired output of data looks like this

enter image description here

1 Answer 1

2

I think need write reshaped DataFrame by unstack with some data cleaning to csv:

df['Count'].unstack().rename_axis(None).rename_axis(None, axis=1).to_csv('example.csv')

Detail:

print (df['Count'].unstack().rename_axis(None).rename_axis(None, axis=1))
           OS  Web
Apple      10   10
Google     10   10
Microsoft  10   10
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.