在 Python Pandas DataFrame 中,我有一个表,我需要在其中计算两个值(开始和停止)之间的总和。问题是,在 DataFrame 中,这可以重复任意次数,但它始终遵循开始、停止、开始、停止模式,在停止和下一个开始之间可能存在一些间隙。
在下面的示例中,我需要在遇到“start”时开始求和,直到遇到“stop”,然后将其报告为一行。然后重复直到数据帧结束。
示例
row val op
0 1 start
1 2
2 5
3 4 stop
4 11
5 10 start
6 20
7 30
8 40 stop
变成
row val op
0 12 start
5 100 start
有没有比for循环(或reduce)不同的方法?也许答案是否定的,只是想确定一下。
最佳答案
这是我的工作。不是最像 Pandas 的,但希望很容易理解。主要思想是首先调用 cumsum ,然后提取与开始/停止行相对应的值
df['cumval']=df['val'].cumsum()
grp = df.groupby('op', as_index=False)
df_start = grp.get_group('start').reset_index()
df_stop= grp.get_group('stop').reset_index()
df_start['val'] = df_stop['cumval'] - df_start['cumval'] + df_start['val']
df_start.drop(['index','cumval'], axis=1, inplace = True)
df_start
关于python - 是否有一种有效的方法来对由特定值标记的行的连续子集求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64688515/