2

I have a code like:

def sample_func(new_df):

   if ( new_df['name'] == 'Tom'):
      return "Yes"
   elif( new_df['name'].isin(['Harry', 'Jerry', 'Savi', 'Aavi'])):
      return "Common Name"
   else:
      return None

I am getting error as:

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

How to fix such errors?

2 Answers 2

3

Use numpy.select:

def sample_func(new_df):

    m1 = new_df['name'] == 'Tom'
    m2 = new_df['name'].isin(['Harry', 'Jerry', 'Savi', 'Aavi'])

    new_df['new'] = np.select([m1, m2], ['Yes','Common Name'], default=None)
    return new_df

More information about your error is here.

Sign up to request clarification or add additional context in comments.

4 Comments

I am getting this error now, "ValueError: shape mismatch: objects cannot be broadcast to a single shape", the scenario for which I am doing this is having different column name in variable m1 and m2.
@Dhiraj - What is print (new_df.columns) ?
@Dhiraj - because I guess there are duplicated column names, 2 or more name columns
I can see the new column with the required values but can you explain me why i am getting the ValueError
0

I have modified your code with any to get the result:-

def sample_func(new_df):
    if any( new_df['name'] == 'Tom'):
        return "Yes"
    elif any( new_df['name'].isin(['Harry', 'Jerry', 'Savi', 'Aavi'])):
        return "Common Name"
    else:
        return None

Output

Yes

I hope it may help you.

4 Comments

I don't see the reason why you converted the elif to else if nested block
@AnkitAgrawal the first else is related to for loop AND this else contains if-else.
yes I know that but why not include it in simple if elif else block as in question @Rahulcharan
@AnkitAgrawal Yes you can write code with if elif else also. I have modified my code, you can see it.

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.