Check if dataframe column is Categorical

后端 未结 5 1930
灰色年华
灰色年华 2020-12-29 00:53

I can\'t seem to get a simple dtype check working with Pandas\' improved Categoricals in v0.15+. Basically I just want something like is_categorical(column) -> True

5条回答
  •  既然无缘
    2020-12-29 01:40

    First, the string representation of the dtype is 'category' and not 'categorical', so this works:

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

    But indeed, as you noticed, this comparison gives a TypeError for other dtypes, so you would have to wrap it with a try .. except .. block.


    Other ways to check using pandas internals:

    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
    

    For non-categorical columns, those statements will return False instead of raising an error. For example:

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

    For much older version of pandas, replace pd.api.types in the above snippet with pd.core.common.

提交回复
热议问题