Arvind Pant
Arvind Pant

Reputation: 65

How to fillna with conditions

I have two columns A and B, there are some blank files in column B. I want to fill '0' in column B when column A = 'BC' and '1' when column A = 'DC'.

Current DataFrame :-

A 	B
BC 
BC 	21
DC 	
DC 	18
BC 	
DC 	

Expected DataFrame:-

A 	B
BC 	0
BC 	21
DC 	1
DC 	18
BC 	0
DC 	1

Upvotes: 1

Views: 96

Answers (1)

BENY
BENY

Reputation: 323396

You can try

#df.B=df.B.repalce({'':np.nan})  
df.B.fillna(df.A.map({'BC':0,'DC':1}),inplace=True)

Or just

df.loc[df.B=='','B']=df.A.map({'BC':0,'DC':1})
df
    A   B
0  BC   0
1  BC  21
2  DC   1
3  DC  18
4  BC   0
5  DC   1

Upvotes: 2

Related Questions