'Pandas dataframe groupby make a list or array of a column

import pandas as pd
import numpy as np

df = {'a': ['aa', 'aa', 'aa', 'aaa', 'aaa'], 
      'b':['bb', 'bb', 'bb', 'bbb', 'bbb'], 
      'c':[10,20,30,100,200]}

df = pd.DataFrame(data=df)

my_dict=df.groupby(['a', 'b'])['c'].apply(np.hstack).to_dict()

gives the following dictionary

>>> my_dict
{('aa', 'bb'): array([10, 20, 30]), ('aaa', 'bbb'): array([100, 200])}

Is there a faster/efficient way of doing this other than using apply?



Solution 1:[1]

You could use groupby and itertuples:

my_dict = dict(df.groupby(['a','b']).agg(list).itertuples(name=None))

{('aa', 'bb'): [10, 20, 30], ('aaa', 'bbb'): [100, 200]}

Or more succinctly, as noted by Ch3steR:

df.groupby(['a','b']).agg(list).to_dict() 


{('aa', 'bb'): [10, 20, 30], ('aaa', 'bbb'): [100, 200]}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 halfer