Check if dataframe column is Categorical

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

    In my pandas version (v1.0.3), a shorter version of joris' answer is available.

    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
    

提交回复
热议问题