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

pandas DataFrame column manipulation using previous row value

I have below pandas DataFrame

color direction Total
-1.0 1.0 NaN
1.0 1.0 0
1.0 1.0 0
1.0 1.0 0
-1.0 1.0 NaN
1.0 -1.0 NaN
1.0 1.0 0
1.0 1.0 0

I am trying to update the total column based on below logic.

if df[‘color’] == 1.0 and df[‘direction’] == 1.0 then Total should be Total of previous row + 1. if Total of previous row is NaN, then 0+1

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

Note: I was trying to read the previous row total using df[‘Total’].shift() + 1 but it didnt work.

Expected DataFrame.

color direction Total
-1.0 1.0 NaN
1.0 1.0 1
1.0 1.0 2
1.0 1.0 3
-1.0 1.0 NaN
1.0 -1.0 NaN
1.0 1.0 1
1.0 1.0 2

>Solution :

You can create the sub-groupby value with cumsum , the new just groupby with color and direction and do cumcount

df.loc[df.Total.notnull(),'Total'] = df.groupby([df['Total'].isna().cumsum(),df['color'],df['direction']]).cumcount()+1
df
Out[618]: 
   color  direction  Total
0   -1.0        1.0    NaN
1    1.0        1.0    1.0
2    1.0        1.0    2.0
3    1.0        1.0    3.0
4   -1.0        1.0    NaN
5    1.0       -1.0    NaN
6    1.0        1.0    1.0
7    1.0        1.0    2.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