Check if dataframe column is Categorical

后端 未结 5 1928
灰色年华
灰色年华 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:39

    Use the name property to do the comparison instead, it should always work because it's just a string:

    >>> 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'
    

    So, to sum up, you can end up with a simple, straightforward function:

    def is_categorical(array_like):
        return array_like.dtype.name == 'category'
    

提交回复
热议问题