根据列值对具有MultiIndex的pandas DataFrame进行排序

编程入门 行业动态 更新时间:2024-10-28 10:23:56
本文介绍了根据列值对具有MultiIndex的pandas DataFrame进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在控制台中打印后,我有一个具有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_values + 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进行排序

本文发布于:2023-10-27 18:38:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534204.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:MultiIndex   pandas   DataFrame

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!