【问题标题】:Dataframe percentile using a rolling value from another column使用来自另一列的滚动值的数据框百分位数
【发布时间】:2019-11-14 17:52:32
【问题描述】:

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

我想获得一个列,它使用滚动 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    ...

谢谢!!

【问题讨论】:

    标签: python pandas dataframe percentile


    【解决方案1】:

    您可以在 pandas 中使用滚动方法。例如:

    df = pd.DataFrame({'B': [0, 1, 2, 2, 4]})
    df['rolling_mean'] = df['B'].rolling(2).mean()
    

    将创建'B'列的两个周期滚动平均值的新列。如果您需要计算不同的汇总统计量,您可以应用不同的方法,例如:

    df['rolling_sum'] = df['B'].rolling(2).sum()
    
    

    有关功能的更多信息,请参阅: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html

    【讨论】:

      【解决方案2】:

      基于this answer,您可以在索引列百分位数的列价格上使用rolling,然后在apply中使用quantile,并带有参数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 参数。

      【讨论】:

      • 这正是我所需要的。谢谢!
      猜你喜欢
      • 2022-01-26
      • 2020-02-05
      • 1970-01-01
      • 2015-02-23
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      • 2015-02-17
      • 1970-01-01
      相关资源
      最近更新 更多