0

I have a simple dataset that I have sorted with dataframe based on 'category'.

The sorting has gone all well. But now, I'd like to export the sorted/adjusted dataset in .xlsx format. That is the dataset that has been categorized, not the dataset that is read in excel.

I have tried the following:

import pandas as pd
df = pd.read_excel("python_sorting_test.xlsx",index_col=[1])

df.head()

print(df.sort_index(level=['Category'], ascending=True))

df.to_excel (r'C:\Users\Laptop\PycharmProjects\untitled8\export_dataframe.xlsx', header=True)

The issue: It doesn't doesn't store the sorted/adjusted dataset.

3
  • Add inplace flag otherwise it does not "save" the sort operation. Commented May 11, 2019 at 12:19
  • Your code doesn't do anything. print(df.sort_index(level=['Category'], ascending=True)) just shows the result of sorting and throws it away. Either use inplace=True or use df = df.sort_index(level=['Category'], ascending=True)) to assign the result back Commented May 11, 2019 at 12:20
  • Thank you for explaining, I noticed the difference. Commented May 11, 2019 at 12:25

1 Answer 1

1

Actually, you doesn't save results of sort_index. You can add inplace=True

print(df.sort_index(level=['Category'], ascending=True, inplace=True))

or save results of df.sort_index

df = df.sort_index(level=['Category'], ascending=True)
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.