我有以下数据帧结构作为示例。
我想获得一个列,它使用滚动 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
,然后使用 quantile
在 apply
中使用参数 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/