根据索引中的关键字汇总行 [英] Summing rows based on keyword within index
本文介绍了根据索引中的关键字汇总行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试根据作为索引一部分的关键字将多个行加在一起-但这不是整个索引.例如,索引可能看起来像
I am trying to sum multiple rows together based on a keyword that is part of the index - but it is not the entire index. For example, the index could look like
Count
1234_Banana_Green 43
4321_Banana_Yellow 34
2244_Banana_Brown 23
12345_Apple_Red 45
我想对其中具有相同关键字"的所有行求和,并创建一个总的香蕉"行.有没有一种方法可以在不搜索关键字"banana"的情况下进行操作?出于我的目的,此关键字每次都会更改,我希望能够自动执行该求和过程.很感谢任何形式的帮助.
I would like to sum all of the rows that have the same "keyword" within them and create a total "banana" row. Is there a way to do this without searching for the keyword "banana"? For my purposes, this keyword changes every time and I would like to be able to automate this summing process. Any help is very much appreciated.
推荐答案
可能是这样:
df.groupby(df.index.to_series()
.str.split('_', expand=True)[1]
)['Count'].sum()
输出:
1
Apple 45
Banana 100
Name: Count, dtype: int64
这篇关于根据索引中的关键字汇总行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文