Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 430
burcak Avatar asked Sep 17 '20 09:09

burcak


2 Answers

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])}
like image 123
jezrael Avatar answered Nov 15 '22 04:11

jezrael


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]}
like image 2
Umar.H Avatar answered Nov 15 '22 03:11

Umar.H