How to sort a Pandas DataFrame by index?
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:
sort
has been deprecated, replaced bysort_index
for this scenario- preferable not to use
inplace
as it is usually harder to read and prevents chaining. See explanation in answer here: Pandas: peculiar performance drop for inplace rename after dropna
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