简体   繁体   English

在 python 中出错为“**系列的真值不明确”

[英]Getting error in python as "**The truth value of a Series is ambiguous"

I am getting the below error when I am trying to perform an if statement and assigning it back to a dataframe column当我尝试执行 if 语句并将其分配回数据框列时出现以下错误

The truth value of a Series is ambiguous.系列的真值是不明确的。 Use a.empty, a.bool(), a.item(), a.any() or a.all().使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

def cal_test():
    if IP['Type'] == 'ABC':
        (IP['tt'] + ' ' + IP[abc])
    else:
        IP[tt]

IP['column_name']  =   cal_test()
IP['column_name'] = IP['tt']
IP.loc[IP['Type'] == 'ABC', 'column_name'] = IP['tt'] + ' ' + IP['abc']

The expression:表达方式:

IP['Type'] == 'ABC'

means to compare a column "Type" of dataframe IP against a string "ABC" , which of course ambiguous -- do you want it to fail because you are comparing apple to orange or do you mean if any of the item in the column match the string?意味着将数据帧IP的列 "Type" 与字符串"ABC" ,这当然是不明确的 - 您是否希望它失败,因为您将苹果与橙色进行比较,或者您的意思是列中的任何项目匹配字符串?

The right way to compare itemize is IP['Type'].eq('ABC') which returns you a column (ie, series) of boolean value, or you can use any or all to mean any value in the column or all values in the column do the match.比较 itemize 的正确方法是IP['Type'].eq('ABC')它返回一个布尔值的列(即系列),或者您可以使用anyall来表示列中的任何值或全部列中的值进行匹配。

And, your function returns nothing.而且,您的函数不返回任何内容。 So you cannot possibly put anything "back" to the dataframe.所以你不可能把任何东西“放回”数据框。 Try do this instead:尝试这样做:

IP['column_name'] = IP.apply(
    lambda row: (row['tt']+' '+row['abc']) if row['Type'] == 'ABC' else
                row['tt'],
    axis=1
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM