使用 `.to_dict()`,pandas 将 python 字典中的 `NaN` 转换为 `nan` ;如何检查 'nan' 是否存在于 python 中

With `.to_dict()`, pandas converts `NaN` to `nan` in python dictionary ; How to check if 'nan' exists in python

这是一个示例 CSV 文件:

X,Y
A,
B,
C,D

阅读此文件后,pandas 将空单元格视为 NaN 值:

df = pd.read_csv("test.csv")
  X   Y
0 A NaN
1 B NaN
2 C   D

并将其转换为 python 词典列表后,NaN 变为 nan

>> d = df.to_dict(orient='records')

[{'X': 'A', 'Y': nan}, {'X': 'B', 'Y': nan}, {'X': 'C', 'Y': 'D'}]

我正在尝试使用 math.isnan() 查找 null 退出的位置,但它抛出异常

for i,v in enumerate(d):
    if math.isnan(v['Y']):
        print(I)
0
1
TypeError: must be real number, not str

可以使用

处理异常
for i,v in enumerate(d):
    try:
        if math.isnan(v['Y']):
            print(i)
    except:
        pass

但是有没有更好的方法来查找 nan 值??

IIUC 使用 pandas.isna:

for i,v in enumerate(d):
    if pd.isna(v['Y']):
        print('I')

您不需要任何功能,您可以将值与自身进行比较。 NaN 有一个有趣的 属性 与它们不同:

for i,v in enumerate(d):
    if v['Y']!=v['Y']:
        print(i)

输出

0
1

另一种可能性是从 DataFrame 本身生成此列表(请注意,您将在此处获得实际索引,因此如果这是范围索引,则为 0、1,否则为索引的第一个和第二个值):

s = df['Y'].isna()
na_indices = s[s].index.to_list()

输出:[0, 1]