在 pandas DataFrame 中的滚动窗口上对数据进行排名

2022-01-11 00:00:00 pandas time-series rank

问题描述

我是 Python 和 Pandas 库的新手,如果这是一个微不足道的问题,我深表歉意.我正在尝试在 N 天的滚动窗口中对时间序列进行排名.我知道有一个排名函数,但这个函数对整个时间序列的数据进行排名.我似乎无法找到滚动排名功能.这是我正在尝试做的一个示例:

I am new to Python and the Pandas library, so apologies if this is a trivial question. I am trying to rank a Timeseries over a rolling window of N days. I know there is a rank function but this function ranks the data over the entire timeseries. I don't seem to be able to find a rolling rank function. Here is an example of what I am trying to do:

           A

01-01-2013 100
02-01-2013 85
03-01-2013 110
04-01-2013 60
05-01-2013 20
06-01-2013 40

如果我想在 3 天的滚动窗口内对数据进行排名,答案应该是:

If I wanted to rank the data over a rolling window of 3 days, the answer should be:

           Ranked_A

01-01-2013 NaN
02-01-2013 Nan
03-01-2013 1
04-01-2013 3
05-01-2013 3
06-01-2013 2

是否有 Python 中的内置函数可以做到这一点?有什么建议吗?非常感谢.

Is there a built-in function in Python that can do this? Any suggestion? Many thanks.


解决方案

如果你想使用 Pandas 内置rank方法(带有一些额外的语义,比如升序选项),你可以为它创建一个简单的函数包装器

If you want to use the Pandas built-in rank method (with some additional semantics, such as the ascending option), you can create a simple function wrapper for it

def rank(array):
    s = pd.Series(array)
    return s.rank(ascending=False)[len(s)-1]

然后可以用作自定义滚动窗口函数.

that can then be used as a custom rolling-window function.

pd.rolling_apply(df['A'], 3, rank)

哪个输出

Date
01-01-2013   NaN
02-01-2013   NaN
03-01-2013     1
04-01-2013     3
05-01-2013     3
06-01-2013     2

(我假设 Rutger 的回答中的 df 数据结构)

(I'm assuming the df data structure from Rutger's answer)

相关文章