在Pandas中,根据特定列的输入为数字这一事实删除了一行

问题描述

根据特定列不是数字的事实,不难删除数据框中的行。但就我而言,我有反对意见。我必须删除与特定列的数字输入相对应的行。

解决方法

使用errors='coerce'将列转换为数字,并测试缺少的值以删除数字值:

df= pd.DataFrame(data={'tested col': [1,'b',2,'3'],'A': [1,3,4]})

print (df)

  tested col  A
0          1  1
1          b  2
2          2  3
3          3  4

df1 = df[pd.to_numeric(df['tested col'],errors='coerce').isna()]
print (df1)
  tested col  A
1          b  2