python - NA 的 bool 值太模糊

标签 python pandas

我正在尝试创建一个具有一些条件的新列。其中之一是“TierType”是否与下面的单元格不同。其次是“ID”是否与下面的行相同。如果满足这些条件,我想返回 1,如果不满足 0。这就是返回值,我觉得这可能是因为 NaN 值,但我删除了数据中的所有 NaN 值。知道为什么我会收到错误消息“TypeError:NA 的 bool 值不明确”(也如图所示)enter image description here

tier_change = df_AC['TierType'] != df_AC['TierType'].shift(1)
sub_ID = df_AC["Subscriber Contact's My Avid ID"] == df_AC["Subscriber Contact's My Avid ID"].shift(1) 
df_AC['Tier_Type_Change_Date'] = np.where((tier_change) & (sub_ID), 1, 0)

最佳答案

表达式(tier_change) & (sub_ID) 是 bool 值。

当 bool 表达式中缺少值时,会引发错误 builtins.TypeError: NA 的 bool 值不明确

在 Pandas 中,缺失值由 pd.NA 表示。

例如,要在 Shell 中重现错误:


>>> import pandas as pd
>>> bool(pd.NA)
...
builtins.TypeError: boolean value of NA is ambiguous

Since the actual value of an NA is unknown, it is ambiguous to convert NA to a boolean value.

来自文档 here

请注意,Pandas 缺失值与空的 Numpy Nan 值并不完全相同,我们可以在 Shell 中进行如下检查:

>>> import numpy as np
>>> bool(np.nan)
True

建议的解决方案

使用 Pandas fillna() 方法将空值替换为最适合您的值来解决问题。

属性测试

import pandas as pd
import numpy as np

df = pd.DataFrame([{'Empty Pandas Value': pd.NA, 'Empty Numpy Value': np.nan}])

print(df)
#   Empty Pandas Value  Empty Numpy Value
# 0               <NA>                NaN

# Replace by 0
zeros = df.fillna(0)
#    Empty Pandas Value  Empty Numpy Value
# 0                   0                0.0

# Or replace by NaN
nans = df.fillna(np.nan)
#    Empty Pandas Value  Empty Numpy Value
# 0                 NaN                NaN

#  ------- Boolean TEST 1 ------- 
df['Empty Pandas Value'] != df['Empty Numpy Value']
# 0    True
# dtype: bool

# ------- Boolean TEST 2 ------- 
df['Empty Pandas Value'].astype(bool)
# ...
# builtins.TypeError: boolean value of NA is ambiguous

# ------- Boolean TEST 3 ------- 
df['Empty Numpy Value'].astype(bool)
# 0    True
# Name: Empty Numpy Value, dtype: bool

关于python - NA 的 bool 值太模糊,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75264528/

相关文章:

python - 使父对象不出现在 before_flush 事件监听器的 session.dirty 中

python - Pandas 的功能与我的预期相反

python - 如何使用 Pandas 中每天变化的固定引用进行计算?

python - 如何使用 BeautifulSoup 获取数据

python - 比较 Python 列表中的元素顺序

Python MySQLdb 错误

python - Pandas - 矢量化 "any element in a column within the next timeframe is True"

python - 列表python中的相对大小

python - 如何连接这两个 pandas 数据框?

python - 日期时间 dtype 是对象而不是日期时间