Group by DataFrame with list and sum

拥有回忆 提交于 2020-03-16 11:32:07

问题


I have a pandas Dataframe df and I want to Group by text column with aggregation of:

  • Stack the english_word and return the list
  • Sum the count column

Now I only can do either making the english_word list or sum the count column. I try to do that, but it return error. How to do both of that aggregation?

In simple, what I want:

text

saya eat chicken

english_word

[eat,chicken]

count

2

df.groupby('text', as_index=False).agg({'count' : lambda x: x.sum(), 'english_word' : lambda x: x.list()})

This is the example of df:

df = pd.DataFrame({'text': ['Saya eat chicken', 'Saya eat chicken'], 
                   'english_word': ['eat', 'chicken'],
                   'count': [1,1]})

回答1:


You are almost there, you can do:

s = df.groupby('text').agg({'word': list, 'num': 'count'}).reset_index()

  text       word  num
0  bla  [i, love]    2

Sample Data

df = pd.DataFrame({'text':['bla','bla'],
                  'word':['i','love'],
                  'num':[1,2,]})



回答2:


Something like this?

def summarise(df):
     return Series(dict(Count = df['count'].sum(), 
                        Words = "{%s}" % ', '.join(df['english_word'])))

new_df = df.groupby('text', as_index=False).agg({'count' : lambda x:x.sum(), 'english_word' : lambda x: x.list()})

new_df.groupby('text').apply(summarise)


来源:https://stackoverflow.com/questions/59949786/group-by-dataframe-with-list-and-sum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!