示例数据:
>>>name food beverage age
0 Ruth Burger Cola 23
1 Dina Pasta water 19
2 Joel Tuna water 28
3 Daniel null soda 30
4 Tomas null cola 10
使用一般方法实现,但不断出错(ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
),具体逻辑如下:
if df[(df['food'].isna())]:
df['beverage']=' '
df['age']=' '
1、使用mask修改
df[['beverage','age']] = df[['beverage','age']].mask(df['food'].isna(),'')
输出结果:
name food beverage age
0 Ruth Burger Cola 23
1 Dina Pasta water 19
2 Joel Tuna water 28
3 Daniel NaN
4 Tomas NaN
2、使用loc修改
可以使用布尔索引来根据条件赋值:
df.loc[df['food'].isna(), ['age', 'beverage']] = ''
输出结果:
name food beverage age
0 Ruth Burger Cola 23
1 Dina Pasta water 19
2 Joel Tuna water 28
3 Daniel NaN
4 Tomas NaN
3、使用np.where修改
cols = ['beverage','age']
arr = np.where(df['food'].isna()[:,None],'',df[cols])
#for NaN : arr = np.where(df['food'].isna()[:,None],np.nan,df[cols])
df[cols] = arr
输出结果:
name food beverage age
0 Ruth Burger Cola 23
1 Dina Pasta water 19
2 Joel Tuna water 28
3 Daniel NaN
4 Tomas NaN