如何确定 Pandas/NumPy 中的列/变量是不是为数字?

Posted

技术标签:

【中文标题】如何确定 Pandas/NumPy 中的列/变量是不是为数字?【英文标题】:How to determine whether a column/variable is numeric or not in Pandas/NumPy?如何确定 Pandas/NumPy 中的列/变量是否为数字? 【发布时间】:2013-11-22 21:23:58 【问题描述】:

有没有更好的方法来确定Pandas 和/或NumPy 中的变量是否为numeric

我有一个自定义的dictionary,其中dtypes 作为键,numeric / not 作为值。

【问题讨论】:

您可以查看dtype.kind in 'biufc' Jaime 发表的评论上面的评论比下面的评论简单,而且似乎效果很好......谢谢 【参考方案1】:

您可以使用 dtypes 检查给定列是否包含数值

numerical_features = [feature for feature in train_df.columns if train_df[feature].dtypes != 'O']

注意:“O”应为大写

【讨论】:

【参考方案2】:

根据@jaime 在 cmets 中的回答,您需要检查 .dtype.kind 以获得感兴趣的列。例如;

>>> import pandas as pd
>>> df = pd.DataFrame('numeric': [1, 2, 3], 'not_numeric': ['A', 'B', 'C'])
>>> df['numeric'].dtype.kind in 'biufc'
>>> True
>>> df['not_numeric'].dtype.kind in 'biufc'
>>> False

NB biufc 的含义:b bool, i int (signed), u unsigned int, f float, c complex。见https://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.kind.html#numpy.dtype.kind

【讨论】:

这里是所有 dtype 种类的列表 [1]。小写u 用于无符号整数;大写 U 用于 unicode。 [1]:docs.scipy.org/doc/numpy/reference/generated/…【参考方案3】:

Pandas 有select_dtype 功能。您可以像这样轻松过滤 int64float64 上的列:

df.select_dtypes(include=['int64','float64'])

【讨论】:

【参考方案4】:

只是添加到所有其他答案,也可以使用df.info() 来获取每一列的数据类型。

【讨论】:

或者只是df.dtypes【参考方案5】:

您可以使用np.issubdtype 来检查数据类型是否是np.number 的子数据类型。例子:

np.issubdtype(arr.dtype, np.number)  # where arr is a numpy array
np.issubdtype(df['X'].dtype, np.number)  # where df['X'] is a pandas Series

这适用于 numpy 的 dtypes,但不适用于 pandas 特定类型,例如 pd.Categorical as Thomas noted。如果您使用的是来自 pandas 的分类 is_numeric_dtype 函数,则它比 np.issubdtype 更好。

df = pd.DataFrame('A': [1, 2, 3], 'B': [1.0, 2.0, 3.0], 
                   'C': [1j, 2j, 3j], 'D': ['a', 'b', 'c'])
df
Out: 
   A    B   C  D
0  1  1.0  1j  a
1  2  2.0  2j  b
2  3  3.0  3j  c

df.dtypes
Out: 
A         int64
B       float64
C    complex128
D        object
dtype: object

np.issubdtype(df['A'].dtype, np.number)
Out: True

np.issubdtype(df['B'].dtype, np.number)
Out: True

np.issubdtype(df['C'].dtype, np.number)
Out: True

np.issubdtype(df['D'].dtype, np.number)
Out: False

对于多列,您可以使用 np.vectorize:

is_number = np.vectorize(lambda x: np.issubdtype(x, np.number))
is_number(df.dtypes)
Out: array([ True,  True,  True, False], dtype=bool)

对于选择,pandas 现在有 select_dtypes:

df.select_dtypes(include=[np.number])
Out: 
   A    B   C
0  1  1.0  1j
1  2  2.0  2j
2  3  3.0  3j

【讨论】:

这似乎不适用于 pandas DataFrames,因为它们可能会返回 numpy 未知的类别,例如“类别”。 Numpy 然后抛出“TypeError:数据类型不理解”【参考方案6】:

只检查列中某个值的类型怎么样?我们一直有这样的事情:

isinstance(x, (int, long, float, complex))

当我尝试检查以下数据框中列的数据类型时,我将它们作为“对象”而不是我期望的数字类型:

df = pd.DataFrame(columns=('time', 'test1', 'test2'))
for i in range(20):
    df.loc[i] = [datetime.now() - timedelta(hours=i*1000),i*10,i*100]
df.dtypes

time     datetime64[ns]
test1            object
test2            object
dtype: object

当我执行以下操作时,它似乎给了我准确的结果:

isinstance(df['test1'][len(df['test1'])-1], (int, long, float, complex))

返回

True

【讨论】:

【参考方案7】:

pandas 0.20.2 你可以这样做:

import pandas as pd
from pandas.api.types import is_string_dtype
from pandas.api.types import is_numeric_dtype

df = pd.DataFrame('A': ['a', 'b', 'c'], 'B': [1.0, 2.0, 3.0])

is_string_dtype(df['A'])
>>>> True

is_numeric_dtype(df['B'])
>>>> True

【讨论】:

我会说这是更优雅的解决方案。谢谢 看来is_numeric_dtype 也为boolean 类型返回True 是的@ManojGovindan,因为布尔值在 Python 中是整数。您可以对它们应用乘法等操作,基本上,Bool 是一个整数,可以取值为 0 或 1。【参考方案8】:

你也可以试试:

df_dtypes = np.array(df.dtypes)
df_numericDtypes= [x.kind in 'bifc' for x in df_dtypes]

它返回一个布尔值列表:True 如果是数字,False 如果不是。

【讨论】:

【参考方案9】:

这是一个伪内部方法,只返回数值类型数据

In [27]: df = DataFrame(dict(A = np.arange(3), 
                             B = np.random.randn(3), 
                             C = ['foo','bar','bah'], 
                             D = Timestamp('20130101')))

In [28]: df
Out[28]: 
   A         B    C                   D
0  0 -0.667672  foo 2013-01-01 00:00:00
1  1  0.811300  bar 2013-01-01 00:00:00
2  2  2.020402  bah 2013-01-01 00:00:00

In [29]: df.dtypes
Out[29]: 
A             int64
B           float64
C            object
D    datetime64[ns]
dtype: object

In [30]: df._get_numeric_data()
Out[30]: 
   A         B
0  0 -0.667672
1  1  0.811300
2  2  2.020402

【讨论】:

是的,我试图弄清楚他们是如何做到的。人们会期望每列运行一个内部 IsNumeric 函数......但仍然没有在代码中找到它 您可以在每列中应用它,但只检查 dtype 就容易多了。无论如何,熊猫操作在需要时都会排除非数字。你想做什么?

以上是关于如何确定 Pandas/NumPy 中的列/变量是不是为数字?的主要内容,如果未能解决你的问题,请参考以下文章

比较 pandas/numpy 中的 NaN 列

pandas -- numpy++

pandas -- numpy++

JAVA中如何取得EXCEL中确定已知的单元格所包含的列数 急急急!!!

pandas/numpy:我有一个数组,里面有一个字典。如何从中创建 DataFrame? [复制]

当特定的列组合确定其重复性时,如何排除sql中的数据?