python - 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'
.
有人可以告诉我为什么会出现该错误以及我应该在代码中进行哪些更改以使其正常工作?
解决方案
您需要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)
推荐阅读
- c++ - 如何将项目与 boost 链接,该项目依赖于另一个使用 boost 的库
- python - 如何修复以下错误以运行简单的 Python 程序?VSCode 终端中的错误
- perl - 如何捕获 Perl 字符串 eval 的输出?
- python - 将 Pandas DataFrame 网格化为多维 Xarray 数据集?
- entity-framework - 如何在 .net core 3.1 中订购具有空值的 IQueryable
- bitbucket - 如何管理管道中未结束的流程?
- python - 如何从 ASP.NET C# 中的 SqlDataSource 获取特定的行值?
- jenkins - 在同一个 Jenkinsfile 中定义多个作业
- snowflake-cloud-data-platform - Snowflake Copy 命令不会在定义的表中插入数据
- python - Django 评论/优化/建议