将pandas.groupby转换为dict

koP*_*tok 4 python dictionary python-3.x pandas pandas-groupby

考虑一下,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
Run Code Online (Sandbox Code Playgroud)

我想按列将它拆分a成字典:

{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}
Run Code Online (Sandbox Code Playgroud)

我发现使用的解决方案pandas.groupby是:

{k: table for k, table in d.groupby("a")}
Run Code Online (Sandbox Code Playgroud)

有哪些其他解决方案?

jpp*_*jpp 10

您可以使用dicttuple/ list应用上的groupby:

res = dict(tuple(d.groupby('a')))
Run Code Online (Sandbox Code Playgroud)