![](/img/trans.png)
[英]Why am I getting a ValueError: The truth value of a Series is ambiguous?
[英]Why am i getting this error "The truth value of a Series is ambiguous" python
我的 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
我正在嘗試創建一個名為 Cat 的新列
使用
df_reps["Cat"] = df_reps["TermCnt"] if df_reps["TermCnt"] < 3 else 99
但得到這個錯誤
ValueError:Series 的真值不明確。 使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
我檢查了這個鏈接
Series 的真值是不明確的。 使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()
似乎有一個不合邏輯的 if 語句
但是當我嘗試這條線時
df_reps["TermCnt"] < 3
我得到這些值
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
這意味着邏輯部分是正確的
知道如何解決嗎?
您可以使用apply()
方法:
df_reps["Cat"]=df_reps["TermCnt"].apply(lambda x:x if x < 3 else 99)
現在如果你打印df_reps
你會得到你想要的 output
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.