首页 > 解决方案 > 从列中过滤掉非数字值

问题描述

我在 pandas DataFrame 中有以下列:

col1
1.2
1.4
3.1
aa
bb
NaN

我需要计算列中的最小值,col1同时忽略所有空值和非数字值。

如果我这样做df[col1].min(),它只会忽略空值,但我仍然会收到此错误:

TypeError: '<=' not supported between instances of 'float' and 'str'

标签: pythonpandas

解决方案


尝试pd.to_numeric()

pd.to_numeric(df.col1,errors='coerce').min()
#1.2
#or df.col1.apply(lambda x: pd.to_numeric(x,errors='coerce')).min() <- slow

推荐阅读