11

I have the following dataframe in pandas:

>>>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

I want to put condistion that if value in food column is null, the age and beverage will change into ' ' (blank as well),

I have wrote this code for that:

if df[(df['food'].isna())]:
  df['beverage']=' '
  df['age']=' '

but I keep getting error:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I have playes with the location of the ([ but didn't help, what do I do wrong?

3 Answers 3

10

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             
Sign up to request clarification or add additional context in comments.

Comments

8

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             

Comments

5

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             

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.