代码之家  ›  专栏  ›  技术社区  ›  enter_display_name_here

计算数据帧中每个滚动第n行之间的百分比变化

  •  1
  • enter_display_name_here  · 技术社区  · 7 年前

    给定以下数据帧:

    >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]})
    

    enter image description here

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

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

    其结果是:

    enter image description here

    另外,作为奖励,我希望以小数点后两位的百分比显示结果输出。

    谢谢你抽出时间!

    1 回复  |  直到 7 年前
        1
  •  1
  •   enter_display_name_here    7 年前

    知道了!对“pct_change()”使用选项“periods”。

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