Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading