我正在尝试向 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)
但是我在理解如何编码方面有些困难。
你有什么想法吗?
非常感谢。
最佳答案
我会推荐for循环..
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]
关于python - 累积自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50798952/