按DataFrame分组并列出列表和总和 [英] Group by DataFrame with list and sum
本文介绍了按DataFrame分组并列出列表和总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个熊猫数据框 df ,我想按 text 列进行分组,汇总如下:
- 堆叠 english_word 并返回列表
- 对 count 列求和
现在我只能做english_word列表或对count列求和。我尝试这样做,但是返回错误。
简单地说,我想要什么:
文本
saya eat chicken
english_word
[吃,鸡]
计数
2
df.groupby('text',as_index = False).agg({'count':lambda x: x.sum(),'english_word':lambda x:x.list()})
此是 df 的示例:
df = pd.DataFrame({'text':[' Saya eat chicken, Saya eat chicken],
'english_word':['eat','chicken'],
'count':[1,1]})
解决方案
您快到了,可以这样做:
s = df.groupby('text')。agg({'word':list,'num':'count'})。reset_index()
文字词num
0 bla [i,love] 2
<块状te>
样本数据
df = pd.DataFrame({'text':['bla','bla'],
'word':['i','love'],
'num':[1, 2,]})
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]})
解决方案
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,]})
这篇关于按DataFrame分组并列出列表和总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文