如何使用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 nanThe 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.
更多推荐
发布评论