Python 数据框中的滚动百分比变化 [英] Rolling percentage change in Python data frame

查看:79
本文介绍了Python 数据框中的滚动百分比变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据框(多行):

I have a dataframe like this (many rows):

       Jan  Feb  Mar  Apr   May  Jun  Jul  Aug  Sep  Oct  Nov  Dec
   a    34   24   47   30    11   57   47   44   22   33   16   39
   b    50   53   42   23    19   29   38   46   21   18   13   24  
   .    .                                                       .
   .
   .    .                                                       .

我想创建一个具有滚动 3 个月百分比变化值的新 df,因此 [1,1] 元素将是 Apr 值和 Jan 值之间的百分比变化,[1,2]元素将是 5 月和 2 月之间的变化百分比等......因此,对于每个值,我希望这个值和 3 个月前的值之间的变化百分比

I would like to create a new df with the rolling 3 month percentage change values, so the [1,1] element will be the % change between the value of Apr and the value of Jan, the [1,2] element wiil be the % change between May and Feb etc... Therefore, for each value, I want the % change between this value and the value 3 months ago

这是我想要的示例输出(例如第一个值是[(30-34)/34]*100 = -11.7):

This is the sample output that I want (for example the first value is [(30-34)/34]*100 = -11.7):

      Apr     May    Jun   Jul     Aug    Sep   Oct   Nov   Dec

  a  -11.7%  -54.1%   0%   56.6%   300%    ..    ..    ..    ..      
  .   .

  .   .

我知道大熊猫有 .pct_change 但这并没有按照我想要的方式计算百分比.关于如何在 python 中执行此操作的任何想法?谢谢

I know that pandas have the .pct_change but this does not calculate the percentages in the way that I want. Any ideas on how I can do this in python? Thank you

推荐答案

使用 pct_change 使用 axis=1periods=3:

df.pct_change(periods=3, axis=1)

输出:

   Jan  Feb  Mar       Apr       May       Jun       Jul       Aug       Sep  \
a  NaN  NaN  NaN -0.117647 -0.541667  0.212766  0.566667  3.000000 -0.614035   
b  NaN  NaN  NaN -0.540000 -0.641509 -0.309524  0.652174  1.421053 -0.275862   

        Oct       Nov       Dec  
a -0.297872 -0.636364  0.772727  
b -0.526316 -0.717391  0.142857  

删除 NaN 列:

df.pct_change(periods=3, axis=1).dropna(1)

输出:

        Apr       May       Jun       Jul       Aug       Sep       Oct       Nov       Dec
a -0.117647 -0.541667  0.212766  0.566667  3.000000 -0.614035 -0.297872 -0.636364  0.772727
b -0.540000 -0.641509 -0.309524  0.652174  1.421053 -0.275862 -0.526316 -0.717391  0.142857

这篇关于Python 数据框中的滚动百分比变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆