python - 浮动对象没有属性 isna
问题描述
我有一个 df ,其中所有列都是对象。为什么我不能应用检查 2 列是否有 NaN 的函数。我想避免np.where
,因为我在函数中有 6 个其他 elif 行。
df
cola_ check1 colb check2
0 The start hungry banana high
1 world NaN apple NaN
2 yesterday fruit pear high
def func(df):
if (df['check1'].isna()) & (df['check2'].isna()):
return df['colb']
df['final'] = df.apply(func, axis=1)
预期产出
cola_ check1 colb check2 final
0 The start hungry banana high
1 world NaN apple NaN apple
2 yesterday fruit pear high
'float' object has no attribute 'isna'
解决方案
您正在将该isna
方法应用于一个浮点对象,如错误所示,该对象没有这样的方法:
>>> import pandas as pd
>>> pd.Series([1, np.nan]).apply(lambda x: x.isna())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/ubuntu/documents/assets/envs/venv/lib/python3.6/site-packages/pandas/core/series.py", line 4212, in apply
mapped = lib.map_infer(values, f, convert=convert_dtype)
File "pandas/_libs/lib.pyx", line 2403, in pandas._libs.lib.map_infer
File "<stdin>", line 1, in <lambda>
AttributeError: 'float' object has no attribute 'isna'
您可以改为使用np.isnan
来测试 float 是否为nan
,如下所示:
>>> pd.Series([1, np.nan]).apply(lambda x: True if not np.isnan(x) else False)
0 True
1 False
dtype: bool
所以你的函数看起来像这样:
def func(df):
try:
test = np.isnan(df['check1']) and np.isnan(df['check2'])
except Exception as e:
if 'not supported for the input types' in str(e):
test = False
else:
raise
return df['colb'] if test else df
您可能会考虑使用其他一些变量名称,func
除了df
按apply
行应用函数,不一定在整个数据帧上。
推荐阅读
- android - 为什么我对“lateinit 属性注入器尚未初始化”感到沮丧?
- reactjs - 如何让 qt webengine 调用响应组件函数
- java - JavaFX FinishListener 空闲方法调用了两次
- json - 如何在 Flutter 中过滤地图?
- docker - 詹金斯似乎在容器内运行
- c++ - 将一组类转换为类模板并避免构造函数歧义
- javascript - 如何将存储在java数组中的数据用于javascript?
- android - FirebaseRemoteConfigFetchException
- javascript - Async/await 在继续之前不会等待数据库查询
- visual-studio - Xamarin Android - 每次在调试模式下重新安装应用程序