df是一个pandas数据框架。 我想找到所有数字类型的列。 喜欢的东西:
isNumeric = is_numeric(df)
df是一个pandas数据框架。 我想找到所有数字类型的列。 喜欢的东西:
isNumeric = is_numeric(df)
当前回答
下面的代码将返回数据集的数字列的名称列表。
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']
其他回答
请参阅以下代码:
if(dataset.select_dtypes(include=[np.number]).shape[1] > 0):
display(dataset.select_dtypes(include=[np.number]).describe())
if(dataset.select_dtypes(include=[np.object]).shape[1] > 0):
display(dataset.select_dtypes(include=[np.object]).describe())
通过这种方式,您可以检查值是数值,如float和int还是srting值。第二个if语句用于检查对象引用的字符串值。
虽然这是一个古老的话题,
但我认为下面的公式比其他的都简单
df [df.describe () .columns]
由于函数describe()仅适用于数值列,因此输出的列将仅为数值列。
很多贴出来的答案都是低效的。这些答案要么返回/选择原始数据帧的子集(不必要的副本),要么在describe()的情况下执行不必要的计算统计。
要获得数字列名,可以使用pd.api.types的条件列表推导式。is_numeric_dtype功能:
numeric_cols = [col for col in df if pd.api.types.is_numeric_dtype(df[col])]
我不确定这个函数是什么时候引入的。
我们可以根据下面的要求包括和排除数据类型:
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]”
你可以使用DataFrame的select_dtypes方法。它包括include和exclude两个参数。所以isNumeric看起来是这样的:
numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
newdf = df.select_dtypes(include=numerics)