Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list inside pandas dataframe cells

I have a data-frame like this:

enter image description here

and I want a new data-frame with a new column which contains a list like this: enter image description here

How do I create a list inside a data-frame cell which contains the elements based on similar month?

like image 878
ultron Avatar asked Mar 13 '26 00:03

ultron


2 Answers

Let try, set_index, groupby, and apply(list):

df.set_index('month', append=True).groupby(level=[0,1,2], sort=False)['from']\
  .apply(list).reset_index('month')

Output:

              month    from
google 2016      2     [e]
apple  2016      1  [b, c]
       2016      3     [l]
google 2016      3     [g]
like image 188
Scott Boston Avatar answered Mar 15 '26 13:03

Scott Boston


Simpliest is use new functionality in pandas 0.20.0+ for groupby by levels and columns together:

df=df.groupby(['client','year','month'], sort=False)['from'].apply(list).reset_index('month')
print (df)
             month    from
client year               
google 2016      2     [e]
apple  2016      1  [b, c]
       2016      3     [l]
google 2016      3     [g]

For scalars with one element list solution is similar Wen - custom function with if else:

df=df.groupby(['client','year','month'], sort=False)['from'] \
     .apply(lambda x: list(x) if len(x)>1 else x.iat[0]).reset_index('month')
print (df)
             month    from
client year               
google 2016      2       e
apple  2016      1  [b, c]
       2016      3       l
google 2016      3       g

And for strings joined by , use join instead list:

df=df.groupby(['client','year','month'], sort=False)['from']
     .apply(', '.join).reset_index('month')
print (df)
             month  from
client year             
google 2016      2     e
apple  2016      1  b, c
       2016      3     l
google 2016      3     g
like image 34
jezrael Avatar answered Mar 15 '26 12:03

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!