Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

pandas - Rolling percentage change in Python data frame

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  
   .    .                                                       .
   .
   .    .                                                       .

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

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%    ..    ..    ..    ..      
  .   .

  .   .

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use pct_change with axis=1 and periods=3:

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

Output:

   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  

Drop NaN columns:

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

Output:

        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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...