我试图计算 pandas 系列的分位数,我使用 for 循环向前查找 n 行,然后计算分位数,但我认为这是一种低效的方法。
我尝试使用滚动函数,但该函数正在向后计算该分位数。
这是我的旧代码:
def calculate_percentile(value,days):
result = []
for index in range(len(df)):
end = index + days +1
#print(index,end)
true_range_percentage = df.iloc[index:end].reset_index()['TR %']
true_range_percentage = df.iloc[index:].reset_index()['TR %'] \ if
len(true_range_percentage) == 0 else true_range_percentage
result.append(true_range_percentage.quantile(value))
return result
效果很好,但花了很多时间。
这是我认为可能更有效的新方法,但我没有向前看,而是从向后获取分位数,我尝试对级数进行逆操作,但没有成功。
df['TR %'].rolling(window=days, min_periods=1).quantile(0.25)
谢谢!
最佳答案
默认情况下插值是线性的,如果您希望它向前,请尝试将插值设置为更高:
df['TR %'].rolling(window=days, min_periods=1).quantile(0.25, interpolation='higher')
关于python - 如何使用 pandas 计算四分位数前滚?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57686061/