检查数据帧列是否为分类变量。

17 浏览
0 Comments

检查数据帧列是否为分类变量。

我似乎无法使用Pandas v0.15+中改进的Categorical类型进行简单的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'])

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

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)
 in ()
----> 1 df.x.dtype == 'category'
TypeError: data type "category" not understood

在Pandas v0.15+中是否有任何方法可以进行这些类型的检查?

0