累积自定义功能

时间:2018-06-11 13:31:47

标签: python pandas apply

我正在尝试向pandas数据框添加一列

import pandas as pd
df = pd.DataFrame([['a',1],['b',0],['c',1],['d',1],['e',0],['f',1]])

这样它包含累积自定义函数的结果

a --> (total + a) * a

即,它取值a,将其与总和相加并乘以结果。在我的例子中,我希望得到输出:

pd.DataFrame([['a',1,1],['b',0,0],['c',1,1],['d',1,2],['e',0,0],['f',1,1]])

我知道这可以使用

完成
df.expanding.apply(some_lambda_function)

但我在理解如何编码方面有些困难。

你有什么想法吗?

非常感谢。

1 个答案:

答案 0 :(得分:1)

我会推荐循环..

start=0
total=[]
for x ,y in df.iterrows():
    start=(y[1]+start)*y[1]
    total.append(start)
total
Out[201]: [1, 0, 1, 2, 0, 1]
相关问题