shreeja7
shreeja7

Reputation: 111

Fill first NaN in each row

I have a input dataframe as

ID  Visit11 Visit12 Visit13 Visit1Int4  Visit15
1   Orange              
2   Orange  Apple   
3   Grapes  
4   Apple   
5   Orange Apple    
6   Apple  
7   Banana  
8   Banana  Apple   Banana  Apple   Banana 

I want to fill the first NA of each row with 'Exit' (SO for ID 1, Visit12 should be 'Exit', for ID2 Visit13 should be 'Exit', etc.). The final output should look like

ID  Visit11 Visit12 Visit13 Visit1Int4  Visit15
1   Orange  Exit            
2   Orange  Apple   Exit         
3   Grapes  Exit            
4   Apple   Exit            
5   Orange Apple    Exit       
6   Apple  Exit             
7   Banana  Exit            
8   Banana  Apple   Banana  Apple   Banana E

Upvotes: 1

Views: 82

Answers (1)

yatu
yatu

Reputation: 88266

You could start by replacing empty values with np.nan, and take the cumsum of DataFrame.isna. Then use np.where to assign Exit where cumsum is 1, or the value in df otherwise:

import numpy as np

m = df.replace('',np.nan).isna().cumsum(axis=1)
r = np.where(m == 1, 'Exit', df)
pd.DataFrame(r, columns=df.columns).fillna('')

   ID  Visit11 Visit12 Visit13 Visit1Int4 Visit15
0   1  Orange    Exit                           
1   2  Orange   Apple    Exit                   
2   3  Grapes    Exit                           
3   4   Apple    Exit                           
4   5  Orange   Apple    Exit                   
5   6   Apple    Exit                           
6   7  Banana    Exit                           
7   8  Banana   Apple  Banana      Apple  Banana

Upvotes: 4

Related Questions