pandas groupby 转置 str 列 [英] pandas groupby transpose str column

查看:71
本文介绍了pandas groupby 转置 str 列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想要做的:

>>>import pandas as pd
>>>dftemp = pd.DataFrame({'a': [1] * 3 + [2] * 3, 'b': 'a a b c d e'.split()})
    a   b
0   1   a
1   1   a
2   1   b
3   2   c
4   2   d
5   2   e
6   3   f

如何转置按列 'a' 分组的列 'b',使输出看起来像:

how to transpose column 'b' grouped by column 'a', so that output looks like:

    a   b0 b1  b2
0   1   a  a   b
3   2   c  d   e
6   3   f  NaN NaN

推荐答案

使用 pivot_tablecumcount:

(df.assign(flag=df.groupby('a').b.cumcount())
    .pivot_table(index='a', columns='flag', values='b', aggfunc='first')
    .add_prefix('B'))

flag B0   B1   B2
a
1     a    a    b
2     c    d    e
3     f  NaN  NaN

这篇关于pandas groupby 转置 str 列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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