pandas 在自定义函数上进行滚动应用

huangapple go评论101阅读模式
英文:

pandas rolling apply on a custom function

问题

我想在滚动基础上应用pandas.rank。
我尝试使用pandas.rolling.apply,但不幸的是rolling不与'rank'一起工作。

有没有解决办法?

  1. df = pd.DataFrame(np.random.randn(10, 3))
  2. def my_rank(x):
  3. return x.rank(pct=True)
  4. df.rolling(3).apply(my_rank)
英文:

I would like to apply pandas.rank on a rolling basis.
I tried to used pandas.rolling.apply but unfortunately rolling doesn't work with 'rank'.

Is there a way around?

  1. df = pd.DataFrame(np.random.randn(10, 3))
  2. def my_rank(x):
  3. return x.rank(pct=True)
  4. df.rolling(3).apply(my_rank)

答案1

得分: 2

代码部分已经翻译如下:

  1. def my_rank(x):
  2. return pd.Series(x).rank(pct=True).iloc[-1}
  3. df.rolling(3).apply(my_rank)

请注意,翻译仅包括代码部分,不包括解释部分。

英文:

Code:

  1. def my_rank(x):
  2. return pd.Series(x).rank(pct=True).iloc[-1]
  3. df.rolling(3).apply(my_rank)

Output:

  1. 0 1 2
  2. 0 NaN NaN NaN
  3. 1 NaN NaN NaN
  4. 2 0.666667 0.333333 0.666667
  5. 3 1.000000 0.333333 1.000000
  6. 4 0.666667 1.000000 0.333333
  7. 5 0.333333 0.666667 0.666667
  8. 6 1.000000 0.333333 0.666667
  9. 7 0.333333 0.333333 1.000000
  10. 8 1.000000 0.666667 1.000000
  11. 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'.
Which meant the x in your my_rank function was getting passed as a numpy array, not a pandas Series. So first I updated return x.rank... to 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. 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. Hence the iloc[-1]

huangapple
  • 本文由 发表于 2020年1月6日 23:46:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615033.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定