Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling NaN with data based on condition

Tags:

python

pandas

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

like image 480
Arnechos Avatar asked Feb 28 '26 04:02

Arnechos


1 Answers

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))
like image 152
cs95 Avatar answered Mar 01 '26 18:03

cs95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!