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
?
Use dictionary comprehension:
my_dict= {k:np.hstack(v) for k, v in df.groupby(['a', 'b'])['c']}
print (my_dict)
{('aa', 'bb'): array([10, 20, 30]), ('aaa', 'bbb'): array([100, 200])}
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]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With