首页 > 解决方案 > 浮动对象没有属性 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'

标签: pythonpython-3.xpandas

解决方案


您正在将该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除了dfapply行应用函数,不一定在整个数据帧上。


推荐阅读