113

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?

Martin Thoma
  • 108,021
  • 142
  • 552
  • 849
midtownguru
  • 2,414
  • 4
  • 20
  • 24

2 Answers2

176

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
Paul H
  • 59,172
  • 18
  • 144
  • 130
  • Note - `inplace` is not recommended : https://github.com/pandas-dev/pandas/issues/16529 – baxx Mar 28 '22 at 11:58
18

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:

fantabolous
  • 18,882
  • 6
  • 51
  • 45
  • 9
    `.sort()` docstring says `DEPRECATED: use DataFrame.sort_values()` – endolith Jul 03 '16 at 17:47
  • 2
    @endolith Indeed `.sort()` has since been deprecated. The replacement would be `.sort_index()` as Paul H uses in his answer, in which case the only difference between our answers is I don't use `inplace=True`. – fantabolous Jan 16 '17 at 23:52