将pandas.groupby转换为dict [英] Convert pandas.groupby to dict

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

问题描述

考虑,数据框d:

d = pd.DataFrame({'a': [0, 2, 1, 1, 1, 1, 1],
                  'b': [2, 1, 0, 1, 0, 0, 2],
                  'c': [1, 0, 2, 1, 0, 2, 2]}
>   a   b   c
0   0   2   1
1   2   1   0
2   1   0   2
3   1   1   1
4   1   0   0
5   1   0   2
6   1   2   2

我想按列a将其拆分成这样的字典:

I want to split it by column a into dictionary like that:

{0:    a  b  c
    0  0  2  1,

 1:    a  b  c
    2  1  0  2
    3  1  1  1
    4  1  0  0
    5  1  0  2
    6  1  2  2,

 2:    a  b  c
    1  2  1  0}

我使用pandas.groupby找到的解决方案是:

The solution I've found using pandas.groupby is:

{k: table for k, table in d.groupby("a")}

还有哪些其他解决方案?

What are the other solutions?

推荐答案

您可以将dicttuple/list应用于groupby一起使用:

You can use dict with tuple / list applied on your groupby:

res = dict(tuple(d.groupby('a')))

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

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