change specific values in dataframe if one cell in a row is null
Try with mask
df[['beverage','age']] = df[['beverage','age']].mask(df['food'].isna(),'')
df
Out[86]:
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
You can use boolean indexing
to assign the values based on the condition:
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
You can use 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