按索引然后按字母顺序对熊猫数据框进行排序

时间:2021-02-19 04:14:19

标签: python pandas

我想按索引对数据帧进行排序,然后按字母顺序排序,以防某些索引值相同。

df = pd.DataFrame()
df['values'] = ['d', 'c', 'b', 'a']
df['index'] = [2, 0, 1, 0]
df = df.set_index('index')

df.sort_index(inplace=True)

哪个输出

      values
index       
0          c
0          a
1          b
2          d

但是,我期待:

      values
index       
0          a
0          c
1          b
2          d

有什么办法可以始终如一地实现这一目标吗?谢谢。

1 个答案:

答案 0 :(得分:4)

根据official documentation,可以将索引名称传入sort_values

df.sort_values(['index','values'])

输出:

      values
index       
0          a
0          c
1          b
2          d

有趣:您还可以按值排序,然后使用稳定算法再次按索引排序:

df.sort_values('values').sort_index(kind='mergesort')