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

use*_*117 58 python numpy pandas

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

我定义了一个自我dictionarydtypes密钥和numeric/ not作为值.

ayh*_*han 69

您可以np.issubdtype用来检查dtype是否是子类型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
Run Code Online (Sandbox Code Playgroud)

这适用于numpy的dtypes,但是对于pandas特定类型(例如pd.Categorical)失败,正如托马斯指出的那样.如果你使用is_numeric_dtypepandas中的分类函数是比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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)

对于多列,您可以使用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)
Run Code Online (Sandbox Code Playgroud)

为了选择,大熊猫现在有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
Run Code Online (Sandbox Code Playgroud)

  • 这似乎不能可靠地与 pandas DataFrames 一起工作,因为它们可能会返回 numpy 未知的类别,例如“类别”。Numpy 然后抛出“TypeError:数据类型不理解” (2认同)

dan*_*ion 61

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
Run Code Online (Sandbox Code Playgroud)

  • 看来“is_numeric_dtype”也为 _boolean_ 类型返回“True”。 (2认同)

dan*_*van 12

根据@ jaime在评论中的回答,您需要检查.dtype.kind感兴趣的列.例如;

>>> import pandas as pd
>>> df = pd.DataFrame({'numeric': [1, 2, 3], 'not_numeric': ['A', 'B', 'C']})
>>> df['numeric'].dtype.kind in 'bifc'
>>> True
>>> df['not_numeric'].dtype.kind in 'bifc'
>>> False
Run Code Online (Sandbox Code Playgroud)

NB bifcb bool, i int, f float, c complex- 我不确定u可能是什么.

  • 这是所有dtype种类的列表[1].小写`u`用于无符号整数; 大写`U`用于unicode.[1]:https://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.kind.html (3认同)

小智 9

熊猫有select_dtype功能。您可以轻松过滤int64float64上的列,如下所示:

df.select_dtypes(include=['int64','float64'])
Run Code Online (Sandbox Code Playgroud)


Jef*_*eff 5

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

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
Run Code Online (Sandbox Code Playgroud)