not bool 不起作用但 bool != True 有效

not bool does not work but bool != True works

我正在尝试从 https://data.cityofnewyork.us/Environment/2018-Central-Park-Squirrel-Census-Squirrel-Data/vfnx-vebw

下载的 CSV 文件中查找唯一颜色列表

以下工作:

data = pandas.read_csv("2018_Central_Park_Squirrel_Census_-_Squirrel_Data.csv")

fur_color_col = data["Primary Fur Color"]
print(data[not pandas.isna(data["Primary Fur Color"])]["Primary Fur Color"].unique())

错误是:

Traceback (most recent call last):
  File "/Users/arvind.avinash/PycharmProjects/AdHoc/main.py", line 6, in <module>
    print(data[not pandas.isna(data["Primary Fur Color"])]["Primary Fur Color"].unique())
  File "/Users/arvind.avinash/PycharmProjects/AdHoc/venv/lib/python3.9/site-packages/pandas/core/generic.py", line 1537, in __nonzero__
    raise ValueError(
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

以下有效

data = pandas.read_csv("2018_Central_Park_Squirrel_Census_-_Squirrel_Data.csv")

fur_color_col = data["Primary Fur Color"]
print(data[pandas.isna(data["Primary Fur Color"]) != True]["Primary Fur Color"].unique())

并输出:

['Gray' 'Cinnamon' 'Black']

为什么 not bool 不起作用而 bool != True 起作用?

因为 non 对于数组(在 pandas 或 numpy 中)是运算符 ~,所以需要:

print(data[~pandas.isna(data["Primary Fur Color"])]["Primary Fur Color"].unique())

为了在数组中进行比较(在 pandas 或 numpy 中)使用与纯 python 中相同的运算符,因此 != True 运行良好。


或者可以使用 Series.notna:

print(data.loc[data["Primary Fur Color"].notna(), "Primary Fur Color"].unique())

not 不起作用的原因是它是 defined by the language spec 到 return 单个布尔值,这对 Pandas 没有多大意义系列。

The operator not yields True if its argument is false, False otherwise.

!=运算符没有这样的限制,这意味着Pandas可以自由定义它作为逐个元素的比较。