Convert pandas.groupby to dict

别等时光非礼了梦想. 提交于 2019-11-26 22:05:12

问题


Consider, dataframe 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

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}

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

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

What are the other solutions?


回答1:


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

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


来源:https://stackoverflow.com/questions/50966466/convert-pandas-groupby-to-dict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!