df是一个pandas数据框架。 我想找到所有数字类型的列。 喜欢的东西:
isNumeric = is_numeric(df)
df是一个pandas数据框架。 我想找到所有数字类型的列。 喜欢的东西:
isNumeric = is_numeric(df)
当前回答
请参阅以下代码:
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.select_dtypes(include=np.number)
如果您想要数值列的名称:
df.select_dtypes(include=np.number).columns.tolist()
完整的代码:
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': range(7, 10),
'B': np.random.rand(3),
'C': ['foo','bar','baz'],
'D': ['who','what','when']})
df
# A B C D
# 0 7 0.704021 foo who
# 1 8 0.264025 bar what
# 2 9 0.230671 baz when
df_numerics_only = df.select_dtypes(include=np.number)
df_numerics_only
# A B
# 0 7 0.704021
# 1 8 0.264025
# 2 9 0.230671
colnames_numerics_only = df.select_dtypes(include=np.number).columns.tolist()
colnames_numerics_only
# ['A', 'B']
虽然这是一个古老的话题,
但我认为下面的公式比其他的都简单
df [df.describe () .columns]
由于函数describe()仅适用于数值列,因此输出的列将仅为数值列。
调整这个答案,你可以做到
df.ix[:,df.applymap(np.isreal).all(axis=0)]
在这里,np.applymap(np.isreal)显示数据帧中的每个单元格是否都是数值,而.axis(all=0)检查列中的所有值是否都为True,并返回一系列可用于索引所需列的布尔值。
简单的一行程序:
df.select_dtypes('number').columns
你可以使用DataFrame的select_dtypes方法。它包括include和exclude两个参数。所以isNumeric看起来是这样的:
numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
newdf = df.select_dtypes(include=numerics)