根据列值对具有MultiIndex的pandas DataFrame进行排序 [英] Sort pandas DataFrame with MultiIndex according to column value
问题描述
在控制台中打印后,我有一个具有MultiIndex的DataFrame:
I have a DataFrame with MultiIndex looking like this after printing in the console:
value indA indB
scenarioId group
2015-04-13 1 A -54.0 1.0 1.0
B -160.0 1.0 1.0
C -15.0 0.0 1.0
2 A -83.0 1.0 1.0
3 A -80.0 2.0 2.0
4 A -270.0 2.0 2.0
2015-04-14 1 A -56.0 1.0 1.0
B -1.0 1.0 1.0
C -60.0 0.0 1.0
2 A -32.0 1.0 1.0
3 A -91.0 2.0 2.0
4 A -17.0 2.0 2.0
在我的初始数据集中使用groupby
和sum
函数后,我得到了它.
I got it after I used the groupby
and sum
functions on my initial dataset.
我想保持相同的格式,但是要根据value
列对其进行排序.我已经尝试使用排序功能来做到这一点,但是我认为拥有MultiIndex的第一个索引(用于日期)没有名称的事实是一个问题.
I would like to keep the same format, but order it according to the value
column. I have tried hard to do it using the sorting functions, but I think that the fact of having the first index (for the dates) of the MultiIndex without name is a problem.
本质上,输出应如下所示:
Essentially, the output should look like this:
value indA indB
scenarioId group
2015-04-13 1 B -160.0 1.0 1.0
A -54.0 1.0 1.0
C -15.0 0.0 1.0
2 A -83.0 1.0 1.0
3 A -80.0 2.0 2.0
4 A -270.0 2.0 2.0
2015-04-14 1 C -60.0 1.0 1.0
A -56.0 1.0 1.0
B -1.0 0.0 1.0
2 A -32.0 1.0 1.0
3 A -91.0 2.0 2.0
4 A -17.0 2.0 2.0
有人可以给我启发吗?
谢谢.
推荐答案
您可以使用 sort_index
:
You can use sort_values
+ sort_index
:
print (df.sort_values('value').sort_index(level=[0,1], sort_remaining=False))
value indA indB
scenarioId group
2015-04-13 1 B -160.0 1.0 1.0
A -54.0 1.0 1.0
C -15.0 0.0 1.0
2 A -83.0 1.0 1.0
3 A -80.0 2.0 2.0
4 A -270.0 2.0 2.0
2015-04-14 1 C -60.0 0.0 1.0
A -56.0 1.0 1.0
B -1.0 1.0 1.0
2 A -32.0 1.0 1.0
3 A -91.0 2.0 2.0
4 A -17.0 2.0 2.0
另一种解决方案- sort_values
与 reset_index
和 set_index
:
Another solution - sort_values
with reset_index
and set_index
:
df = df.reset_index()
.sort_values(['level_0','scenarioId','value'])
.set_index(['level_0','scenarioId','group'])
print (df)
value indA indB
level_0 scenarioId group
2015-04-13 1 B -160.0 1.0 1.0
A -54.0 1.0 1.0
C -15.0 0.0 1.0
2 A -83.0 1.0 1.0
3 A -80.0 2.0 2.0
4 A -270.0 2.0 2.0
2015-04-14 1 C -60.0 0.0 1.0
A -56.0 1.0 1.0
B -1.0 1.0 1.0
2 A -32.0 1.0 1.0
3 A -91.0 2.0 2.0
4 A -17.0 2.0 2.0
这篇关于根据列值对具有MultiIndex的pandas DataFrame进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!