本文介绍了将函数应用于 pandas 系列的累积值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在熊猫中是否存在等价于rolling_apply的函数,该函数将函数应用于一系列累加值而不是滚动值?我意识到cumsumcumprodcummaxcummin存在,但是我想应用自定义函数.

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.

推荐答案

您可以使用 pd.expanding_apply .下面是一个简单的示例,它实际上只进行累加和,但是您可以编写所需的任何函数.

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

这篇关于将函数应用于 pandas 系列的累积值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 10:24