How to sort a Pandas DataFrame by index?

PythonPandas

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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:

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmidtownguruView Question on Stackoverflow
Solution 1 - PythonPaul HView Answer on Stackoverflow
Solution 2 - PythonfantabolousView Answer on Stackoverflow