pandas :如何按列和索引对数据框进行排序 [英] Pandas: how to sort dataframe by column AND by index
本文介绍了 pandas :如何按列和索引对数据框进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出数据框:
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列的值和索引进行排序.
Now, I would like to sort by values of Column A AND the index.
例如
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
如何在列上首先进行排序,然后在索引上进行索引?
How can I get a sort on the column first and index second?
推荐答案
使用numpy中的lexsort
可能是另一种方式,并且速度也稍慢一些:
Using lexsort
from numpy may be other way and little faster as well:
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
使用重置索引并再次设置索引:
With reset index and set index again:
%%timeit
df.reset_index().sort_values(by=['A','index']).set_index('index')
结果:
100 loops, best of 3: 2.09 ms per loop
这篇关于 pandas :如何按列和索引对数据框进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文