简体   繁体   English

使用基于条件的数据填充NaN

[英]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. 返回 - DataFrame的真值是不明确的。 Use a.empty, a.bool(), a.item(), a.any() or a.all(). 使用a.empty,a.bool(),a.item(),a.any()或a.all()。

I have tried with doing like a mask and then applying it with a.all() but it didn't worked out. 我尝试过做像掩码然后用a.all()应用它,但它没有成功。 I'd be very thankful for enlightment! 我非常感谢你的启发!

Edit: I've solution for my problem right here - Link 编辑:我在这里解决我的问题 - 链接

This is an elementwise operation, and you can vectorize this. 这是一个元素操作,您可以对其进行矢量化。 Build an array with np.where and pass that to fillna . 使用np.where构建一个数组并将其传递给fillna

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

你可以这样做

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM