Arnechos
Arnechos

Reputation: 73

Filling NaN with data based on condition

My code looks like that:

if df['FLAG'] == 1:
    df['VAL'] = df['VAL'].fillna(median)
elif df['FLAG'] == 0:
    df['VAL'] = df['VAL'].fillna(0)

Which returns - The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I have tried with doing like a mask and then applying it with a.all() but it didn't worked out. I'd be very thankful for enlightment!

Edit: I've solution for my problem right here - Link

Upvotes: 3

Views: 86

Answers (2)

BENY
BENY

Reputation: 323226

You may can do this

 df.loc[df['VAL'].isna(),'Val']=df['FLAG']*median

Upvotes: 1

cs95
cs95

Reputation: 402483

This is an elementwise operation, and you can vectorize this. Build an array with np.where and pass that to fillna.

df['VAL'] = df['VAL'].fillna(np.where(df['FLAG'], median, 0))

Upvotes: 4

Related Questions