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

[亡魂溺海] 提交于 2021-01-27 22:06:51

问题


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


回答1:


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)  



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/59350625/why-am-i-getting-valueerror-the-truth-value-of-a-series-is-ambiguous-use-a-emp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!