df是一个pandas数据框架。 我想找到所有数字类型的列。 喜欢的东西:

isNumeric = is_numeric(df)

当前回答

这是另一个简单的代码,用于在pandas数据帧中查找数字列,

numeric_clmns = df.dtypes[df.dtypes != "object"].index 

其他回答

你可以使用DataFrame的select_dtypes方法。它包括include和exclude两个参数。所以isNumeric看起来是这样的:

numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']

newdf = df.select_dtypes(include=numerics)
df.select_dtypes(exclude = ['object'])

更新:

df.select_dtypes(include= np.number)

或者是熊猫的新版本

 df.select_dtypes('number')

我们可以根据下面的要求包括和排除数据类型:

train.select_dtypes(include=None, exclude=None)
train.select_dtypes(include='number') #will include all the numeric types

参考自木星笔记本。

要选择所有数字类型,请使用np。Number或' Number '

要选择字符串,必须使用对象dtype,但请注意 这将返回所有对象dtype列 参见NumPy dtype层次结构<http://docs.scipy.org/doc/numpy/reference/arrays.scalars.html>__ 要选择日期时间,使用np。Datetime64, 'datetime'或 “datetime64” 要选择时间增量,使用np。Timedelta64, 'timedelta'或者 “timedelta64” 要选择Pandas分类dtypes,使用'category' 要选择Pandas datetimetz类型,使用'datetimetz'(在 0.20.0)或“datetime64[ns, tz]”

下面的代码将返回数据集的数字列的名称列表。

cnames=list(marketing_train.select_dtypes(exclude=['object']).columns)

这里marketing_train是我的数据集,select_dtypes()是使用exclude和include参数选择数据类型的函数,columns用于获取数据集的列名 以上代码的输出如下:

['custAge',
     'campaign',
     'pdays',
     'previous',
     'emp.var.rate',
     'cons.price.idx',
     'cons.conf.idx',
     'euribor3m',
     'nr.employed',
     'pmonths',
     'pastEmail']
    

很多贴出来的答案都是低效的。这些答案要么返回/选择原始数据帧的子集(不必要的副本),要么在describe()的情况下执行不必要的计算统计。

要获得数字列名,可以使用pd.api.types的条件列表推导式。is_numeric_dtype功能:

numeric_cols = [col for col in df if pd.api.types.is_numeric_dtype(df[col])]

我不确定这个函数是什么时候引入的。