python - 使用另一列的滚动值的数据框百分位

标签 python pandas dataframe percentile

我有以下数据帧结构作为示例。

我想获得一个列,它使用滚动 n 周期回溯根据“百分位数”列的值计算“价格列”的百分位数。

这可能吗?我尝试使用某种 lambda 函数并使用 .apply 语法,但无法使其工作。

        date     percentile  price   desired_row
    2019-11-08  0.355556    0.6863    36th percentile of price of last n period
    2019-11-11  0.316667    0.6851    32nd percentile of price of last n period
    2019-11-12  0.305556    0.6841    ...
    2019-11-13  0.302778    0.6838    ...
    2019-11-14  0.244444    0.6798    ...

谢谢!!

最佳答案

基于this answer ,您可以对价格列和索引中的百分位数使用rolling,然后使用 quantileapply 中使用参数 raw=False:

window = 3
df['desired_row'] = df.set_index('percentile')['price'].rolling(window)\
                      .apply(lambda x: x.quantile(q=x.index[-1]), raw=False).values
print (df)
         date  percentile   price  desired_row
0  2019-11-08    0.355556  0.6863          NaN
1  2019-11-11    0.316667  0.6851          NaN
2  2019-11-12    0.305556  0.6841     0.684711
3  2019-11-13    0.302778  0.6838     0.683982
4  2019-11-14    0.244444  0.6798     0.681756

您可以根据需要更改quantile中的interpolation参数。

关于python - 使用另一列的滚动值的数据框百分位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58862991/

相关文章:

Python通过成功重复现有的字符串元素来创建一个新列表

python - 检查用户输入是否包含数组中的单词 - Python 3

python - 根据变量范围合并行

python - 使用 Python 函数读取 CSV 文件

Pandas 将空对象列添加到数据框

dataframe - 在 MATLAB 中按值对数据进行排序

python - 为什么我的文件没有打开?

python - 显示网页中的所有链接

python - 通过引用传递可变对象?

python - Pandas - 从现有列创建多个默认列