Groupby转置并附加到Pandas中? [英] Groupby, transpose and append in Pandas?

查看:631
本文介绍了Groupby转置并附加到Pandas中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

  userid name1 name2 ... name10 

code>

这意味着我需要反转列 name 的每10条记录和追加到一个新的数据框。



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

code>然后 reset_index 在每个组内一致枚举。然后 unstack 来获得列。

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



演示



  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()



<如果您不希望 userid 作为索引,请在结尾处添加 reset_index

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


I have a dataframe which looks like this:

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

userid  name1  name2  ... name10

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

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

解决方案

groupby('userid') then reset_index within each group to enumerate consistently across groups. Then unstack to get columns.

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()

if you don't want the userid as the index, add reset_index to the end.

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

这篇关于Groupby转置并附加到Pandas中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆