如果我有这样的列表,则命名为“ list_of_words”:
['Haha', 'No', 'Why']
和这样的数据框:
Letter Count
1 Yes 2
2 Haha 3
3 Why 4
4 No 9
5 Teeth 8
我想这样创建一个结果数据框,其中“ list_of_words”中“信”列中的值所在的任何行都被分组在一起并重命名为“其他”:
Letter Count
1 Yes 2
2 Other 16
5 Teeth 8
第一个想法是Series.replace
在aggregate之前使用sum
,但随后所有重复项都将被聚合:
list_of_words = ['Haha', 'No', 'Why']
df['Letter'] = df['Letter'].replace(list_of_words, 'Other')
df = df.groupby('Letter', as_index=False).sum()
print (df)
Letter Count
0 Other 16
1 Teeth 8
2 Yes 2
如果需要,仅汇总来自的单词list_of_words
:
list_of_words = ['Haha', 'No', 'Why']
m = df['Letter'].isin(list_of_words)
df = pd.concat([df[~m],
df[m].assign(Letter = 'Other').groupby('Letter', as_index=False).sum()],
ignore_index=True)
print (df)
Letter Count
0 Yes 2
1 Teeth 8
2 Other 16
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句