【发布时间】:2019-11-30 16:23:05
【问题描述】:
我有以下系列:
my_series = pd.Series([np.nan, np.nan, ['A', 'B']])
我必须遍历 my_series 并评估该值是否为 NaN,然后执行某些操作(为简单起见,将操作定义为“做 A”和“做 B”)。
第一次尝试:
for element in my_series:
if element.isna():
print('do A')
else:
print('do B')
运行时出现错误:"'float' object has no attribute 'isna'"
第二次尝试来自问题:Error: float object has no attribute notnull
for element in my_series:
np.where(element.isnull(), 'do A', 'do B')
运行时出现错误:“AttributeError: 'float' object has no attribute 'isnull'”
我在 StackOverflow 上没有找到任何其他类似的问题,我不知道还能尝试什么。
【问题讨论】:
-
尝试在第二个循环中使用
np.isnan():for element in my_series: np.where(np.isnan(element), 'do A', 'do B') -
尝试并得到以下错误:“输入类型不支持 ufunc 'isnan',并且根据转换规则 ''safe'' 无法安全地将输入强制转换为任何支持的类型”
-
糟糕,然后试试
pd.isna():for element in my_series: np.where(pd.isna(element), 'do A', 'do B')