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

How to get values based on each last valid occurrence in Pandas dataframe

Status Energy
1 2
1 3
1 2
1 4
0 12
0 13
0 11
1 3
0 15
0 14

I have Dataframe with two columns: status and energy. I am trying to create a new column for energy loss based on the last occurrence of each status. I have already tried cumsum with resetting, but it’s not working. Looking for results like the below table. Just copying the Energy column value to result in column based on the last of each status occurrence.

|Status |Energy |Result_outcome|
|:----  |:----  |:----        |
|1      |2      |NaN          |
|1      |3      |NaN          |
|1      |2      |NaN          |
|1      |4      |4            |
|0      |12     |NaN          |
|0      |13     |NaN          |
|0      |11     |11           |
|1      |3      |3            |
|0      |15     |NaN          |
|0      |14     |14           |

>Solution :

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

Let us use shift to compare the current row and next row then update the values in result column based on the outcome of comparison

df.loc[df['Status'] != df['Status'].shift(-1), 'result'] = df['Energy']

   Status  Energy  result
0       1       2     NaN
1       1       3     NaN
2       1       2     NaN
3       1       4     4.0
4       0      12     NaN
5       0      13     NaN
6       0      11    11.0
7       1       3     3.0
8       0      15     NaN
9       0      14    14.0
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