简体   繁体   English

大熊猫滚动适用于自定义函数

[英]pandas rolling apply on a custom function

I would like to apply pandas.rank on a rolling basis.我想滚动应用 pandas.rank 。 I tried to used pandas.rolling.apply but unfortunately rolling doesn't work with 'rank'.我尝试使用 pandas.rolling.apply 但不幸的是滚动不适用于“等级”。

Is there a way around?有办法吗?

df = pd.DataFrame(np.random.randn(10, 3))

def my_rank(x):
   return x.rank(pct=True)

df.rolling(3).apply(my_rank)

Code:代码:

def my_rank(x):
   return pd.Series(x).rank(pct=True).iloc[-1]

df.rolling(3).apply(my_rank)

Output:输出:

          0         1         2
0       NaN       NaN       NaN
1       NaN       NaN       NaN
2  0.666667  0.333333  0.666667
3  1.000000  0.333333  1.000000
4  0.666667  1.000000  0.333333
5  0.333333  0.666667  0.666667
6  1.000000  0.333333  0.666667
7  0.333333  0.333333  1.000000
8  1.000000  0.666667  1.000000
9  0.666667  1.000000  0.666667

Explanation:解释:

Your code (great minimal reproduceable example btw!) threw the following error: AttributeError: 'numpy.ndarray' object has no attribute 'rank' .您的代码(顺便说一句,伟大的最小可复制示例!)引发了以下错误: AttributeError: 'numpy.ndarray' object has no attribute 'rank' Which meant the x in your my_rank function was getting passed as a numpy array, not a pandas Series.这意味着my_rank函数中的x将作为 numpy 数组传递,而不是my_rank系列。 So first I updated return x.rank... to return pd.Series(x).rank..所以首先我更新了return x.rank...return pd.Series(x).rank..

Then I got the following error: TypeError: cannot convert the series to <class 'float'> Which makes sense, because pd.Series.rank takes a series of n numbers and returns a (ranked) series of n numbers.然后我得到以下错误: TypeError: cannot convert the series to <class 'float'>这是有道理的,因为pd.Series.rank需要一系列 n 数字并返回一个(排名)系列的 n 数字。 But since we're calling rank not once on a series, but repeatedly on a rolling window of a series, we only want one number as output for each rolling calculation.但是由于我们不是在一个系列上调用 rank 一次,而是在一个系列的滚动窗口上重复调用,所以我们只需要一个数字作为每个滚动计算的输出。 Hence the iloc[-1]因此iloc[-1]

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

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