When there is an DataFrame like the following:
import pandas as pd df = pd.DataFrame([1, 1, 1, 1, 1], index=[100, 29, 234, 1, 150], columns=['A'])
How can I sort this dataframe by index with each combination of index and column value intact?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Dataframes have a sort_index method which returns a copy by default. Pass inplace=True to operate in place.
import pandas as pd df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A']) df.sort_index(inplace=True) print(df.to_string())
Gives me:
A 1 4 29 2 100 1 150 5 234 3
Method 2
Slightly more compact:
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A']) df = df.sort_index() print(df)
Note:
sorthas been deprecated, replaced bysort_indexfor this scenario- preferable not to use
inplaceas it is usually harder to read and prevents chaining. See explanation in answer here:
Pandas: peculiar performance drop for inplace rename after dropna
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0