python - 使用滚动窗口 Pandas 计算百分位数

标签 python pandas dataframe percentile

我创建了一个 pandas 数据框作为

df = pd.DataFrame(data=[[1],[2],[3],[1],[2],[3],[1],[2],[3]])
df
Out[19]: 
   0
0  1
1  2
2  3
3  1
4  2
5  3
6  1
7  2
8  3

我在长度为 3 的窗口上计算 75% 的百分位数

df.rolling(window=3,center=False).quantile(0.75)
Out[20]: 
     0
0  NaN
1  NaN
2  2.0
3  2.0
4  2.0
5  2.0
6  2.0
7  2.0
8  2.0

然后只是为了检查我在第一个窗口上分别计算了 75%

df.iloc[0:3].quantile(0.75)
Out[22]: 
0    2.5
Name: 0.75, dtype: float64

为什么我得到不同的值?

最佳答案

这是一个错误,在 GH9413 中引用和 GH16211 .

开发者给出的原因 -

It looks like the difference here is that quantile and percentile take the weighted average of the nearest points, whereas rolling_quantile simply uses one the nearest point (no averaging).

Rolling.quantile 在计算分位数时没有插值。

该错误已从 0.21 开始修复。


对于旧版本,修复是使用 rolling_apply

df.rolling(window=3, center=False).apply(lambda x: pd.Series(x).quantile(0.75))

     0
0  NaN
1  NaN
2  2.5
3  2.5
4  2.5
5  2.5
6  2.5
7  2.5
8  2.5

关于python - 使用滚动窗口 Pandas 计算百分位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49453440/

相关文章:

python - 在 Pandas 中,如何使用一个表中的值作为索引从另一个表中提取数据?

r - 列名中的破折号产生 "object not found"错误

python - 两个客户端无法在套接字客户端-服务器连接中相互通信

python - Django 无法连接到 SQL Server 2019

python - os.rename 说无法访问该文件,因为它正在被另一个进程使用

python - 根据发生情况合并行,同时维护 Python 中 DataFrame 中的唯一值

python - 如何只保留 pandas DataFrame 中具有多个值的行?

python - Numpy Logarithm 适用于 bool Pandas 系列,但不适用于 Dataframe 中的 bool 列

pandas - 删除某些变量中没有有限值的 pandas 数据帧行

pandas - 多项式回归给出错误 "shapes (18,17) and (1140,1) not aligned: 17 (dim 1) != 1140 (dim 0)"