Python 如何按特定列对多级数据帧进行排序?
我希望按列对多索引数据帧进行排序,但不希望同时对整个数据帧进行排序。而是想按其中一个指数进行排序。下面是我的意思的一个例子:下面是一个多索引数据帧的例子Python 如何按特定列对多级数据帧进行排序?,python,pandas,Python,Pandas,我希望按列对多索引数据帧进行排序,但不希望同时对整个数据帧进行排序。而是想按其中一个指数进行排序。下面是我的意思的一个例子:下面是一个多索引数据帧的例子 first second bar one 0.361041 two 0.476720 baz one 0.565781 two 0.848519 foo one 0.405524 two 0.882497 qux
first second
bar one 0.361041
two 0.476720
baz one 0.565781
two 0.848519
foo one 0.405524
two 0.882497
qux one 0.488229
two 0.303862
我想要的是:
first second
bar two 0.476720
one 0.361041
baz two 0.848519
one 0.565781
foo two 0.882497
one 0.405524
qux two 0.488229
one 0.303862
我想根据第三列(即数字)对数据帧进行排序,并保持0级索引不变。我们如何做到这一点?使用排序的二级值:
a = s.reindex(sorted(s.index.levels[1], reverse=True), level=1)
print (a)
first second
bar two 0.476720
one 0.361041
baz two 0.848519
one 0.565781
foo two 0.882497
one 0.405524
qux two 0.303862
one 0.488229
Name: a, dtype: float64
您可以使用对索引进行排序,并将布尔值[True,False]
传递给升序
参数
df.sort_index(level=[0,1],ascending=[True,False])
Unnamed: 2
first second
bar two 0.476720
one 0.361041
baz two 0.848519
one 0.565781
foo two 0.882497
one 0.405524
qux two 0.303862
one 0.488229
我不明白你的问题。你能澄清一下吗?
s.loc[('qux','three')]=1.03490
将重新编制three
添加到每个组吗?@Ch3steR-你是对的,编辑了需求的答案s.reindex(['two','three','one','three','three level=1)
我试图这样重新编制索引,但是'three和'three没有添加到每个组。它应该添加right并填充NaNs right?@Ch3steR-hmm,对我来说工作正确,s.loc[('qux','three')]=1.03490
这就是我刚才提到的。