如何使用groupby / pivot修改以下数据框?(How to modify the following dataframe using groupby/pivot?)

编程入门 行业动态 更新时间:2024-10-15 16:22:01
如何使用groupby / pivot修改以下数据框?(How to modify the following dataframe using groupby/pivot?)

我有以下熊猫数据框:

我想按以下方式更改此数据框:我想要将ID列作为索引,并将月份设置为名为month的列中的每个索引,然后将所有值设置为如下所示:

ID MONTH VAL 1 Jan nan 1 Feb nan 1 Mar nan 1 Apr nan 1 May nan 1 Jun nan 1 Jul nan 1 Aug 94.0000 1 Sep 113.0000 1 Oct 21.0000 1 Nov nan 2 Jan 107.00000 . . . 7 Nov nan

月份的顺序并不重要。 有没有简单的方法来做到这一点?

I have the following pandas dataframe:

I want to change this dataframe in the following way: I want to have the ID column as index and the month for each index in a column named month, and then all the values as follow:

ID MONTH VAL 1 Jan nan 1 Feb nan 1 Mar nan 1 Apr nan 1 May nan 1 Jun nan 1 Jul nan 1 Aug 94.0000 1 Sep 113.0000 1 Oct 21.0000 1 Nov nan 2 Jan 107.00000 . . . 7 Nov nan

The order of the month is not important. Is there an easy way to do it?

最满意答案

尝试将dropna参数设置为False的stack :

df.set_index('ID').stack(dropna=False)

@PaulH在他的观点中从下面的评论中是正确的。

将列索引移动到行索引从宽数据框转换为长数据框。

Try stack with dropnaparameter set to False:

df.set_index('ID').stack(dropna=False)

@PaulH is correct in his observations from the comments below.

To move that column index to row index converting from a wide dataframe to a long dataframe.

更多推荐

本文发布于:2023-07-14 14:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1105125.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   数据   groupby   pivot   modify

发布评论

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

>www.elefans.com

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