检查数据帧列是否为分类

Check if dataframe column is Categorical

提问人:Marius 提问时间:11/14/2014 最后编辑:Marius 更新时间:5/13/2022 访问量:66128

问:

我似乎无法在 v0.15+ 中使用 Pandas 改进的分类进行简单的 dtype 检查。基本上我只想要这样的东西.is_categorical(column) -> True/False

import pandas as pd
import numpy as np
import random

df = pd.DataFrame({
    'x': np.linspace(0, 50, 6),
    'y': np.linspace(0, 20, 6),
    'cat_column': random.sample('abcdef', 6)
})
df['cat_column'] = pd.Categorical(df2['cat_column'])

我们可以看到 for 分类列是 'category':dtype

df.cat_column.dtype
Out[20]: category

通常,我们可以通过与名称进行比较来进行 dtype 检查 的 dtype:

df.x.dtype == 'float64'
Out[21]: True

但是在尝试检查列是否 是绝对的:x

df.x.dtype == 'category'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-22-94d2608815c4> in <module>()
----> 1 df.x.dtype == 'category'

TypeError: data type "category" not understood

有什么方法可以在 pandas v0.15+ 中进行这些类型的检查吗?

Python 熊猫

评论

7赞 Jeff 11/14/2014
因此,除了下面的解决方案之外,选择列 >= 0.15.0 的规范方法是df.select_dtypes(include=['category'])
3赞 Antoine Gallix 2/5/2018
这可能与pandas添加的数据类型有关,与来自numpy的其他数据类型相比。category
1赞 JoseOrtiz3 4/30/2019
@AntoineGallix 是的,问题是检查数据类型名称“category”是否是可识别的类别名称(如“float64”)。由于它无法识别(numpy中没有分类数据类型),numpy假设您打错了字,而不是告诉您它绝对不是您要查找的数据类型。另一方面,熊猫选择了另一种方法,错别字导致平淡无奇。numpy.dtypenumpyFalse
0赞 Joris 12/28/2021
我注意到 df.x.dtype == 'category' 在 Pandas 1.3.4 中有效,但在 Pandas 1.0.3 中无效

答:

33赞 joris 11/14/2014 #1

首先,dtype 的字符串表示形式是 和 not ,所以这有效:'category''categorical'

In [41]: df.cat_column.dtype == 'category'
Out[41]: True

但实际上,正如你所注意到的,这个比较为其他 dtype 提供了一个,所以你必须用一个块来包装它。TypeErrortry .. except ..


使用 pandas 内部检查的其他方法:

In [42]: isinstance(df.cat_column.dtype, pd.api.types.CategoricalDtype)
Out[42]: True

In [43]: pd.api.types.is_categorical_dtype(df.cat_column)
Out[43]: True

对于非分类列,这些语句将返回,而不是引发错误。例如:False

In [44]: pd.api.types.is_categorical_dtype(df.x)
Out[44]: False

对于更旧版本的 ,将上面的代码片段替换为 。pandaspd.api.typespd.core.common

评论

0赞 information_interchange 11/11/2021
它会为哪些列提供错误?
0赞 joris 11/13/2021
对于最新版本的 numpy,这不再是错误,但以前类似引发错误而不是返回 False。np.dtype("int64" == "category"
0赞 Trenton McKinney 9/5/2023
这会导致 FutureWarning。请改用此答案中所示的用途pandas v2.1.0isinstance(df.x, pd.CategoricalDtype)
93赞 Jeff Tratner 11/14/2014 #2

改用该属性进行比较,它应该始终有效,因为它只是一个字符串:name

>>> import numpy as np
>>> arr = np.array([1, 2, 3, 4])
>>> arr.dtype.name
'int64'

>>> import pandas as pd
>>> cat = pd.Categorical(['a', 'b', 'c'])
>>> cat.dtype.name
'category'

因此,总而言之,您最终可以得到一个简单、直接的函数:

def is_categorical(array_like):
    return array_like.dtype.name == 'category'
6赞 gosuto 10/24/2019 #3

只是把这个放在这里,因为熊猫。DataFrame.select_dtypes() 是我真正想要的:

df['column'].name in df.select_dtypes(include='category').columns

感谢@Jeff。

5赞 DieterDP 4/2/2020 #4

在我的 pandas 版本 (v1.0.3) 中,可以使用 joris 答案的较短版本。

df = pd.DataFrame({'noncat': [1, 2, 3], 'categ': pd.Categorical(['A', 'B', 'C'])})

print(isinstance(df.noncat.dtype, pd.CategoricalDtype))  # False
print(isinstance(df.categ.dtype, pd.CategoricalDtype))   # True

print(pd.CategoricalDtype.is_dtype(df.noncat)) # False
print(pd.CategoricalDtype.is_dtype(df.categ))  # True

评论

1赞 alexandre iolov 7/7/2020
我的数据 '' isinstance(Tmanual['X'], pd.CategoricalDtype) Out[216]: false tmanual['REVENUES_FAST'].dtype.name == 'category' out[217]: true tmanual['X'].dtype out[218]: CategoricalDtype(categories=['ANY', 'ANYIMPORTANT', 'BX', 'OPTIONAL'], ordered=False) ''
3赞 Pierre Massé 9/17/2020 #5

我遇到了这个线程,寻找完全相同的功能,并且还从此处的 pandas 文档中找到了另一种选择。

看起来检查 pandas 数据帧列是否为分类序列的规范方法应如下:

hasattr(column_to_check, 'cat')

因此,根据初始问题中给出的示例,这将是:

hasattr(df.x, 'cat') #True
0赞 Miguel Gonzalez 2/16/2022 #6

看看 Tratner @Jeff回答,因为条件不需要被视为 cataegorical 列, 我建议考虑对“categorical_dtypes”列表中的 dtypes 进行分类:df.cat_column.dtype == 'category'True

def is_cat(column):
    categorical_dtypes = ['object', 'category', 'bool']
    if column.dtype.name in categorical_dtypes:
        return True
    else:
        return False   

´´´