Pandas遍历DataFrame判断category类型报TypeError如何解决?
报错原因
你触发报错是因为Pandas的CategoricalDtype类型对象在部分版本中无法直接和字符串'category'做相等性判断,底层没有实现对应类型的比较逻辑,就会抛出「data type 'category' not understood」的类型错误。
可行解决方法
- 方案1:用Pandas官方提供的类型判断API(兼容性最好,全版本支持)
import pandas as pd for col in app_train: if pd.api.types.is_categorical_dtype(app_train[col]): # 你的分类字段处理逻辑 pass
- 方案2:判断dtype的name属性
for col in app_train: if app_train[col].dtype.name == 'category': # 你的分类字段处理逻辑 pass
- 方案3:不需要遍历,直接批量提取所有分类字段(Pandas原生方法,性能比自行遍历更高,适合大多数筛选分类列的场景)
# 直接拿到所有category类型的列组成的新DataFrame category_df = app_train.select_dtypes(include='category') # 也可以直接拿到分类列的列名列表 category_cols = app_train.select_dtypes(include='category').columns.tolist()
内容的提问来源于stack exchange,提问作者chuky pedro
相关产品推荐
相关产品推荐

