Home > Enterprise >  Pandas apply groupby list to column containing list
Pandas apply groupby list to column containing list

Time:12-14

I have the following dataframe df:

Col1    Col2
A       'AD'
A       ['FG', 'LKL']
B       ['FGT']

I am trying the following:

df.groupby('Col1')['Col2'].apply(list)

I get the following:

Col1    Col2
A       ['AD', "['FG', 'LKL']"]
B       ['FGT']

I need to get the following:

Col1    Col2
A       ['AD', 'FG', 'LKL']
B       ['FGT']

CodePudding user response:

You can do explode

out = df.explode('Col2').groupby('Col1')['Col2'].apply(list)
  • Related