Home > database >  Python Pandas – How to calculate percentage difference row wise for a entire dataframe with NaNs
Python Pandas – How to calculate percentage difference row wise for a entire dataframe with NaNs

Time:12-06

For a dataframe like this:

route   col1    col2    col3    col4    col5
1       NaN     9       9       9       NaN
2       9       48      NaN     118     NaN
3       68      70      118     106     NaN
4       9       NaN     9       9       48

I would like to get their row wise growth % in a new dataframe like this:

route   col1    col2    col3    col4    col5
1       NaN     NaN     0       NaN     NaN
2       NaN     433.33  NaN     NaN     NaN
3       NaN     2.94    68.57   -10.16  NaN
4       NaN     NaN     NaN     0       433.33

Many thanks

CodePudding user response:

Use pct_change:

>>> df[['route']].join(df.filter(like='col').pct_change(axis=1).mul(100).round(2))

   route  col1    col2   col3    col4    col5
0      1   NaN     NaN   0.00    0.00    0.00
1      2   NaN  433.33   0.00  145.83    0.00
2      3   NaN    2.94  68.57  -10.17    0.00
3      4   NaN    0.00   0.00    0.00  433.33
  • Related