首页 > 解决方案 > 在数据框中检测数据输入错误的问题

问题描述

我有一个数据框 lexdata,我想检查并计算空值的数量,并在“销售列”的某些列中检测无效值

样本数据

     city   year    month   sales   
 0  Abilene  2000   1       72.0    
 1  Abilene  2000   2       ola-k   
 2  Abilene  2000   3       130.0   
 3  Abilene  2000   4       lee 
 4  Abilene  2000   5       141.0

我使用以下代码成功检查并计算了空值:

lexdata.isnull().sum()

挑战是检查销售列中的无效值(字符串)

标签: pythondataframe

解决方案


可以使用pd.to_numeric并传递coerceerrors参数,它会尝试将值转换为数字,如果不能转换为数字,则返回NaN,最后您可以计算null转换后的值

pd.to_numeric(df['sales'], errors='coerce').isnull().sum()

#output: 2

推荐阅读