【问题标题】:Calculate the percent change between every rolling nth row in a Pandas DataFrame计算 Pandas DataFrame 中每个滚动第 n 行之间的百分比变化
【发布时间】:2019-01-13 12:53:24
【问题描述】:

如何计算 Pandas DataFrame 中每个滚动第 n 行之间的百分比变化?以每第二行为例:

给定以下数据框:

>df = pd.DataFrame({"A":[14, 4, 5, 4, 1, 55], 
               "B":[5, 2, 54, 3, 2, 32],  
               "C":[20, 20, 7, 21, 8, 5], 
               "D":[14, 3, 6, 2, 6, 4]})

我希望生成的 DataFrame 是:

但是,我使用此代码得到的最接近:

>df.iloc[::2,:].pct_change(-1)

结果如下:

它每隔一行执行一次计算,但这与每隔 n 行计算一次的滚动窗口不同。我遇到了一个类似的 Stack 帖子,但这个例子不是很简单。

另外,作为奖励,我想以百分比形式显示结果输出到小数点后两位。

感谢您的宝贵时间!

【问题讨论】:

    标签: python-3.x pandas dataframe percentage


    【解决方案1】:

    知道了!为 'pct_change()' 使用选项“句点”。

    >df.pct_change(periods=-n) #where n=2 for the given example.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-22
      • 1970-01-01
      • 2020-12-25
      • 1970-01-01
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      相关资源
      最近更新 更多