Saswat Ray
Saswat Ray

Reputation: 197

How to maintain mutiindex view in pandas while converting pandas dataframe to csv file?

I have pandas dataframe where mutiindex is there(pic 1) but when i am converting it csv it not showing as multiindex(pic 2)

I am using to_csv() .Is there any parameter i need to pass to get right format?

pic 1: enter image description here

pic:2

enter image description here

Tried as per suggestion, below is the pic

enter image description here

Upvotes: 1

Views: 119

Answers (3)

Vivek Kalyanarangan
Vivek Kalyanarangan

Reputation: 9081

I guess you are using an older version of pandas. If you are using <0.21.0, there is a tupleize_cols parameter you can play with. If above, just save as to_csv. It will default to each index in one row -

enter image description here

Upvotes: 0

berkayln
berkayln

Reputation: 995

Maybe this can be helpful for you:

    pd.DataFrame(df.columns.tolist()).T.to_csv("dataframe.csv", mode="w", header=False, index=False)

    df.to_csv("dataframe.csv", mode="a", header=False, index=False)

Upvotes: 0

Henry James
Henry James

Reputation: 145

If you're not bothered about getting a CSV as output the way I do this is by putting the data in an XLSX file.

# Create the workbook to save the data within
workbook = pd.ExcelWriter(xlsx_filename, engine='xlsxwriter')

# Create sheets in excel for data
df.to_excel(workbook, sheet_name='Sheet1')

# save the changes
workbook.save()

Can you try this and see if it formats how you want?

Upvotes: 1

Related Questions