从列中过滤掉非数字值

时间:2019-04-03 19:05:49

标签: python pandas

我在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'

2 个答案:

答案 0 :(得分:3)

尝试使用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

答案 1 :(得分:1)

我认为这是两个步骤:

  1. 将列中的所有元素转换为数字类型。 NaN是数字类型,因此将所有字符串值强制转换为NaN是安全的。
  2. 在得到的(已清除)列上调用min

要执行第一步,请尝试测试每个元素以查看它是否为numbers.Numberthe base class for all Python numeric types的实例。 如果是,则返回该元素。如果不是,请返回NaN

import numbers
import numpy as np

def coerce_to_numeric(value):
    if isinstance(value, numbers.Number):
        return value
    else:
        return np.NaN

# Returns a cleaned version of df[col1]
clean_col = df[col1].apply(coerce_to_numeric)

然后只需添加.min()即可获得已清除列的最小值。

clean_col.min()