查找支持列表和集合以及整数和字符串的混合数据类型的空单元格

find empty cells with support for mixed datatypes of lists and sets and ints and str

考虑以下数据框。

import pandas as pd
my_df = pd.DataFrame(columns =['A','B','C'])
my_df.at[0,'A'] = 1234
my_df.at[0,'C'] = ['5','6','7']
my_df.at[1,'A'] = set([8,9,10])
my_df.at[1,'B'] = 'my_hat'

然后我想找到所有为nan的单元格。

for row_index, row_data in my_df.iterrows():
   for cell in row_data:
      if pd.isnull(cell):
          print("found one")

pd.isnull、pd.isna、pd.notnull都无法处理lists/sets和ints/str的混合。

请注意这是一个非常简化的示例,我需要使用 if 语句测试每个单元格,检测 nans。

编辑:
如果你真的需要检查每个单元格的 NaN,你可以在 my_df.isna() 上进行,例如

for row_index, row_data in my_df.isna().iterrows():
   for cell in row_data:
      if cell:
          print("found one")

试试看你的 for 循环的输出。我取出 if 行以显示 for 循环中 cell 的所有值:

for row_index, row_data in my_df.iterrows():
    for cell in row_data:
        print(cell)

Output:

1234
nan
['5', '6', '7']
{8, 9, 10}
my_hat
nan

现在试试:

pd.isnull(['5', '6', '7'])

Out[3183]: array([False, False, False])

pd.isnull 接受 scalar or array-like 和 returns bool or array-like of bool。您的 cell 之一是数组,因此它 returns 是一个布尔值数组。比较真实的布尔值数组是不明确的,所以 pandas 只是抛出错误。

如果要在df中检查'NaN',请直接在df

上调用isnaisnull
my_df.isna()   

或者需要调用pd.isnull整体df

pd.isnull(my_df)

Out[3181]:
       A      B      C
0  False   True  False
1  False  False   True