Muhuri.JSON
Muhuri.JSON

Reputation: 173

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

The following code gives me Value Error:

major_males=[]

for row in recent_grads:
    if recent_grads['Men']>recent_grads['Women']:
        major_males.append(recent_grads['Major'])
display(major_males)  

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

Upvotes: 3

Views: 1537

Answers (3)

abhilb
abhilb

Reputation: 5757

That is because you are comparing a series and not a value. I guess your intension was if row['Men'] > row['Women']

Secondly it will be more efficient to do


major_males = recent_grads[recent_grads.Men > recent_grads.Women].Major.to_list()

Upvotes: 2

ATL
ATL

Reputation: 591

If recent_grads is a dataframe, then this is how your for loop would look like

major_males=[]

for i, row in recent_grads.iterrows():
    if row['Men']>row['Women']:
        major_males.append(row['Major'])
display(major_males)  

Upvotes: 2

Jacob Brazeal
Jacob Brazeal

Reputation: 654

Note that, while you're iterating over the data frame, you're not using the row variable. Instead, try:

major_males=[]

for row in recent_grads:
    if row['Men']>row['Women']:
        major_males.append(row['Major'])
display(major_males)  

You get the error because it's not meaningful to compare all the Men values to all the Women values: instead you want to compare one specific value of each at a time, which is what the change does.

Upvotes: 0

Related Questions