如何按索引对Pandas DataFrame排序?


91

当有如下所示的DataFrame时:

import pandas as pd
df = pd.DataFrame([1, 1, 1, 1, 1], index=[100, 29, 234, 1, 150], columns=['A'])

如何完整地使用索引和列值的每种组合按索引对该数据帧进行排序?

Answers:


149

数据框具有sort_index默认情况下返回副本的方法。通过inplace=True操作就位。

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())

给我:

     A
1    4
29   2
100  1
150  5
234  3

13

稍紧凑:

df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)

注意:


9
.sort()docstring说DEPRECATED: use DataFrame.sort_values()
endolith

1
@endolith实际上.sort()从那以后就已经过时了。替换将.sort_index()如Paul H在其答案中使用的那样,在这种情况下,我们答案之间的唯一区别是我不使用inplace=True
疯狂
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.