Counting the Number of Preceding Non-NA Rows in a Pandas Dataframe

Python

 1|  INPUT:
 2|  
 3|  	col_1	col_2
 4|  0	NaN	NaN
 5|  1	25.0	NaN
 6|  2	67.0	19.0
 7|  3	86.0	34.0
 8|  
 9|  CODE:
10|  
11|  df = df.notna().cumsum()
12|  
13|  OUTPUT:
14|  
15|  	col_1	col_2
16|  0	0	0
17|  1	1	0
18|  2	2	1
19|  3	3	2
20|  
Did you find this snippet useful?

Sign up for free to to add this to your code library