我想计算给定列中的运行总和(当然不使用循环).需要注意的是,我有另一列指定何时将运行总和重置为该行中存在的值.最佳解释如下:
reset val desired_col
0 0 1 1
1 0 5 6
2 0 4 10
3 1 2 2
4 1 -1 -1
5 0 6 5
6 0 4 9
7 1 2 2
desired_col是我想要计算的值.
解决方法:
你可以使用2次cumsum():
# reset val desired_col
#0 0 1 1
#1 0 5 6
#2 0 4 10
#3 1 2 2
#4 1 -1 -1
#5 0 6 5
#6 0 4 9
#7 1 2 2
df['cumsum'] = df['reset'].cumsum()
#cumulative sums of groups to column des
df['des']= df.groupby(['cumsum'])['val'].cumsum()
print df
# reset val desired_col cumsum des
#0 0 1 1 0 1
#1 0 5 6 0 6
#2 0 4 10 0 10
#3 1 2 2 1 2
#4 1 -1 -1 2 -1
#5 0 6 5 2 5
#6 0 4 9 2 9
#7 1 2 2 3 2
#remove columns desired_col and cumsum
df = df.drop(['desired_col', 'cumsum'], axis=1)
print df
# reset val des
#0 0 1 1
#1 0 5 6
#2 0 4 10
#3 1 2 2
#4 1 -1 -1
#5 0 6 5
#6 0 4 9
#7 1 2 2