如何计算使用熊猫向前滚动的四分位数?

时间:2019-08-28 06:11:47

标签: python pandas rolling-computation

我试图计算熊猫系列的分位数,我使用的是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)

谢谢!

1 个答案:

答案 0 :(得分:0)

默认情况下,插值是线性的,如果希望它可以尝试将插值设置为更高:

df['TR %'].rolling(window=days, min_periods=1).quantile(0.25, interpolation='higher')
相关问题