简体   繁体   English

为什么我会收到此错误“系列的真值不明确”python

[英]Why am i getting this error "The truth value of a Series is ambiguous" python

My dataframe df_reps look like this我的 dataframe df_reps 看起来像这样

        RepID  TermCnt 
0           1       12 
1           1        4 
2           1        3 
3           1        4 
4           1        2 
      ...      ...  ...
1116984  4999        3 
1116985  4999        2 
1116986  4999        1 
1116987  4999        2 
1116988  4999        1 

I am trying to create a new column called Cat我正在尝试创建一个名为 Cat 的新列

using使用

df_reps["Cat"] = df_reps["TermCnt"] if df_reps["TermCnt"] < 3 else 99

but getting this error但得到这个错误

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

I checked this link我检查了这个链接

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

and it is seems there is a non logical if statement似乎有一个不合逻辑的 if 语句

but when I try this line但是当我尝试这条线时

df_reps["TermCnt"] < 3

I get these values我得到这些值

df_reps["TermCnt"] < 3
Out[96]: 
0          False
1          False
2          False
3          False
4           True
 
1116984    False
1116985     True
1116986     True
1116987     True
1116988     True
Name: TermCnt, Length: 1116989, dtype: bool

which means the logical part is correct这意味着逻辑部分是正确的

any idea how to fix that?知道如何解决吗?

You can use apply() method:您可以使用apply()方法:

df_reps["Cat"]=df_reps["TermCnt"].apply(lambda x:x if x < 3 else 99)

Now if you print df_reps you will get your desired output现在如果你打印df_reps你会得到你想要的 output

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

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