简体   繁体   English

对熊猫系列的累积值应用函数

[英]Apply function on cumulative values of pandas series

Is there an equivalent of rolling_apply in pandas that applies function to the cumulative values of a series rather than the rolling values?rolling_apply中是否有等效的rolling_apply将函数应用于系列的累积值而不是滚动值? I realize cumsum , cumprod , cummax , and cummin exist, but I'd like to apply a custom function.我意识到cumsumcumprodcummaxcummin存在,但我想申请一个自定义的功能。

You can use pd.expanding_apply .您可以使用pd.expanding_apply Below is a simple example which only really does a cumulative sum, but you could write whatever function you wanted for it.下面是一个简单的例子,它只计算累计总和,但你可以为它编写任何你想要的函数。

import pandas as pd

df = pd.DataFrame({'data':[10*i for i in range(0,10)]})

def sum_(x):
    return sum(x)


df['example'] = pd.expanding_apply(df['data'], sum_)

print(df)

#   data  example
#0     0        0
#1    10       10
#2    20       30
#3    30       60
#4    40      100
#5    50      150
#6    60      210
#7    70      280
#8    80      360
#9    90      450

[Follow up to @Ffisegydd's answer] [跟进@Ffisegydd 的回答]

Update for pandas == 1.0.5大熊猫更新 == 1.0.5

df['example'] = df['data'].expanding().apply(sum_)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM