将 lambda 函数应用于 Pandas 滚动窗口系列 [英] Applying lambda function to a pandas rolling window series
问题描述
我有一个函数,它接受一个数组和一个值,并返回一个值.我想在滚动的基础上将它应用于我的系列 s
,因此数组始终是滚动窗口.这是我尝试过的(未成功)的最小示例,使用 np.random.choice
代替我的真实函数.我找到了很多用于查找滚动均值和其他内置函数的示例,但无法使其适用于我的任意 lambda 函数.
s = pd.Series([1,2,3,4,5,6,7,8,9])滚动窗口 = s.rolling(3)
第一次尝试:
new_values = s.apply(lambda x: np.random.choice(rolling_window, size=1))
<块引用>
ValueError: a [a is the first positional param of choice(), so reference to 'rolling_window'] 必须是一维或整数
另一种尝试:
new_values = rolling_window.apply(lambda x: np.random.choice(size=1))
<块引用>
TypeError: choice() 至少需要 1 个位置参数(0 给定)
...如何对系列中的每个值、系列中的每个滚动数组窗口应用任意 lambda 函数(采用数组和值)?
IIUC,如果你想做的只是在窗口上应用一个函数,你的第二次尝试就接近了:
rolling_window.apply(lambda x: np.random.choice(x, size=1))
<小时>
但是,您可以像这样绕过 lambda
的使用:
rolling_window.apply(np.random.choice, kwargs={'size' : 1})0 南1 纳米2 1.03 4.04 4.05 5.06 7.07 7.08 8.0数据类型:float64
传递给函数的附加参数在 args
和 kwargs
中.
I have a function which takes an array and a value, and returns a value. I would like to apply it to my Series s
on a rolling basis, so the array is always the rolling window. Here's a minimal example of what I've tried (unsuccessfully), using np.random.choice
in place of my real function. I find lots of examples for finding rolling means and other built-in functions, but can't get it to work for my arbitrary lambda function.
s = pd.Series([1,2,3,4,5,6,7,8,9])
rolling_window = s.rolling(3)
First attempt:
new_values = s.apply(lambda x: np.random.choice(rolling_window, size=1))
ValueError: a [a is the first positional param of choice(), so refers to 'rolling_window'] must be 1-dimensional or an integer
Another attempt:
new_values = rolling_window.apply(lambda x: np.random.choice(size=1))
TypeError: choice() takes at least 1 positional argument (0 given)
...How do I apply an arbitrary lambda function (taking an array and a value) on each value in my Series, on each rolling-array window in my Series?
IIUC, if all you want to do is apply a function on the window, your second attempt comes close:
rolling_window.apply(lambda x: np.random.choice(x, size=1))
However, you can circumvent the use of the lambda
like this:
rolling_window.apply(np.random.choice, kwargs={'size' : 1})
0 NaN
1 NaN
2 1.0
3 4.0
4 4.0
5 5.0
6 7.0
7 7.0
8 8.0
dtype: float64
Additional arguments to the function you pass go in args
and kwargs
.
这篇关于将 lambda 函数应用于 Pandas 滚动窗口系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!