Convert pandas.groupby to dict

11,585

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

res = dict(tuple(d.groupby('a')))
Share:
11,585
koPytok
Author by

koPytok

Updated on June 01, 2022

Comments

  • koPytok
    koPytok almost 2 years

    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?

  • koPytok
    koPytok almost 6 years
    Do you know any groupby method convenient for that?
  • jpp
    jpp almost 6 years
    @Kopytok, No, it's not possible. A groupby doesn't, in itself, create a dict. You need to pass it to dict after some manipulation.
  • jtlz2
    jtlz2 about 2 years
    What about get_group()?
  • jpp
    jpp about 2 years
    @jtlz2, Good suggestion, have added as an alternative.