在 Pandas 中分组、转置和追加?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38369424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:35:04  来源:igfitidea点击:

Groupby, transpose and append in Pandas?

python-3.xpandasgroup-bypandas-groupby

提问by Dawny33

I have a dataframe which looks like this:

我有一个如下所示的数据框:

enter image description here

在此处输入图片说明

Each user has 10 records. Now, I want to create a dataframe which looks like this:

每个用户有 10 条记录。现在,我想创建一个如下所示的数据框:

userid  name1  name2  ... name10

which means I need to invert every 10 records of the column nameand append to a new dataframe.

这意味着我需要反转列的每 10 条记录name并附加到新的数据帧。

So, how do it do it? Is there any way I can do it in Pandas?

那么,它是如何做到的呢?有什么办法可以在 Pandas 中做到吗?

采纳答案by piRSquared

groupby('userid')then reset_indexwithin each group to enumerate consistently across groups. Then unstackto get columns.

groupby('userid')然后reset_index在每个组内以一致的方式枚举跨组。然后unstack得到列。

df.groupby('userid')['name'].apply(lambda df: df.reset_index(drop=True)).unstack()

Demonstration

示范

df = pd.DataFrame([
        [123, 'abc'],
        [123, 'abc'],
        [456, 'def'],
        [123, 'abc'],
        [123, 'abc'],
        [456, 'def'],
        [456, 'def'],
        [456, 'def'],
    ], columns=['userid', 'name'])

df.sort_values('userid').groupby('userid')['name'].apply(lambda df: df.reset_index(drop=True)).unstack()

enter image description here

在此处输入图片说明

if you don't want the useridas the index, add reset_indexto the end.

如果您不想将userid用作索引,请添加reset_index到末尾。

df.sort_values('userid').groupby('userid')['name'].apply(lambda df: df.reset_index(drop=True)).unstack().reset_index()

enter image description here

在此处输入图片说明