检查dataframe列是否为Categorical

Mar*_*ius 36 python pandas

我似乎无法在v0.15 +中使用Pandas改进的Categoricals进行简单的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'])
Run Code Online (Sandbox Code Playgroud)

我们可以看到,dtype分类列是"类别":

df.cat_column.dtype
Out[20]: category
Run Code Online (Sandbox Code Playgroud)

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

df.x.dtype == 'float64'
Out[21]: True
Run Code Online (Sandbox Code Playgroud)

但是,当尝试检查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
Run Code Online (Sandbox Code Playgroud)

有没有办法在pandas v0.15 +中进行这些类型的检查?

Jef*_*ner 41

使用该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'
Run Code Online (Sandbox Code Playgroud)

总而言之,您最终可以得到一个简单,直接的功能:

def is_categorical(array_like):
    return array_like.dtype.name == 'category'
Run Code Online (Sandbox Code Playgroud)


jor*_*ris 17

首先,dtype的字符串表示是'category'和否'categorical',所以这适用:

In [41]: df.cat_column.dtype == 'category'
Out[41]: True
Run Code Online (Sandbox Code Playgroud)

但实际上,正如你所注意到的,这种比较给出了TypeError其他dtypes,所以你必须用一个try .. 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
Run Code Online (Sandbox Code Playgroud)

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

In [44]: pd.api.types.is_categorical_dtype(df.x)
Out[44]: False
Run Code Online (Sandbox Code Playgroud)

对于更旧的版本pandas,请pd.api.types在上面的代码段中替换pd.core.common.


jor*_*mit 5

把它放在这里是因为这pandas.DataFrame.select_dtypes()是我真正想要的:

df['column'].name in df.select_dtypes(include='category').columns
Run Code Online (Sandbox Code Playgroud)

感谢@Jeff。


Die*_*rDP 5

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