Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
547 views
in Technique[技术] by (71.8m points)

python - 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? I realize cumsum, cumprod, cummax, and cummin exist, but I'd like to apply a custom function.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...