pandas :GroupBy到DataFrame [英] Pandas: GroupBy to DataFrame

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

问题描述

有一个非常受欢迎的S.O.有关分组依据到数据框的问题,请参见此处.不幸的是,我认为这个特定的用例不是最有用的.

There is a very popular S.O. question regarding groupby to dataframe see here. Unfortunately, I do not think this particular use case is the most useful.

假设您拥有扁平化形式的分层数据集:

Suppose you have what could be a hierarchical dataset in a flattened form:

例如

     key    val 
0    'a'    2
1    'a'    1
2    'b'    3
3    'b'    4

我要做的就是将该数据帧转换为这种结构

what I wish to do is convert that dataframe to this structure

    'a'  'b'
0    2    3
1    1    4

我认为这很简单

pd.DataFrame(df.groupby('key').groups)

但不是.

那么我该如何进行转换?

So how can I make this transformation?

推荐答案

df.assign(index=df.groupby('key').cumcount()).pivot('index','key','val')
Out[369]: 
key    'a'  'b'
index          
0        2    3
1        1    4

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

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