Pandas:如何按列和按索引对数据框进行排序

时间:2018-03-19 01:48:35

标签: python pandas sorting dataframe

鉴于DataFrame:

import pandas as pd
df = pd.DataFrame([6, 4, 2, 4, 5], index=[2, 6, 3, 4, 5], columns=['A'])

结果:

   A
2  6
6  4
3  2
4  4
5  5

现在,我想按列A和索引的值进行排序。

e.g。

df.sort_values(by='A')

返回

   A
3  2
6  4
4  4
5  5
2  6

我希望

   A
3  2
4  4
6  4
5  5
2  6

如何首先对列进行排序并将索引排在第二位?

3 个答案:

答案 0 :(得分:6)

您可以使用kind='mergesort'按索引排序,然后按A列排序。

这是因为mergesort is stable

res = df.sort_index().sort_values('A', kind='mergesort')

结果:

   A
3  2
4  4
6  4
5  5
2  6

答案 1 :(得分:6)

使用来自numpy的df.iloc[np.lexsort((df.index, df.A.values))] # Sort by A.values, then by index 可能是另一种方式,但也快一点:

   A
3  2
4  4
6  4
5  5
2  6

结果:

timeit

%%timeit df.iloc[np.lexsort((df.index, df.A.values))] # Sort by A.values, then by index 比较:

1000 loops, best of 3: 278 µs per loop

结果:

 %%timeit
df.reset_index().sort_values(by=['A','index']).set_index('index')

再次使用重置索引和设置索引:

100 loops, best of 3: 2.09 ms per loop

结果:

{{1}}

答案 2 :(得分:0)

其他答案很好。我将提出另一个选择,即首先使用rename_axis为索引提供名称,然后在sort_values中引用它。我尚未测试性能,但希望可接受的答案仍然更快。

df.rename_axis('idx').sort_values(by=['A', 'idx'])

     A
idx   
3    2
4    4
6    4
5    5
2    6

如果需要,可以随后使用df.index.name = None清除索引名称。

相关问题