首页 > 解决方案 > Pandas 应用函数,接收 KeyError 'Column Name'

问题描述

我的数据集有一个名为的列age,我正在尝试计算空值。

我知道它可以通过执行类似的操作轻松实现len(df) - df['age'].count()。但是,我正在玩弄函数,只是想应用函数来计算空计数。

这是我所拥有的:

def age_is_null(df):
    age_col = df['age']
    null = df[age_col].isnull()
    age_null = df[null]
    return len(age_null)

count = df.apply(age_is_null)
print (count)

当我这样做时,我收到一个错误:KeyError: 'age'.

有人可以告诉我为什么会出现该错误以及我应该在代码中进行哪些更改以使其正常工作?

标签: pythonpandas

解决方案


您需要DataFrame.pipe或传递 DataFrame 才能在此处运行:

#function should be simplify
def age_is_null(df):
    return df['age'].isnull().sum()


count = df.pipe(age_is_null)
print (count)

count = age_is_null(df)
print (count)

错误意味着如果使用DataFrame.apply则按列迭代,因此如果要选择列则失败age

def func(x):
   print (x)

df.apply(func)

编辑:对于选择列使用列名:

def age_is_null(df):
    age_col = 'age' <- here
    null = df[age_col].isnull()
    age_null = df[null]
    return len(age_null)

或为掩码传递选定的列:

def age_is_null(df):
    age_col = df['age']
    null = age_col.isnull()  <- here
    age_null = df[null]
    return len(age_null)

推荐阅读