如何在Pandas中获取指定值对应的分类对象?
获取CategoricalDtype中对应值的分类对象
你可以通过创建包含目标值的Categorical数组,再提取对应元素的方式实现需求,具体方案如下:
方法1:直接创建单元素Categorical数组
import pandas as pd cat_type = pd.api.types.CategoricalDtype(categories=['c1', 'c2', 'c3', 'c4']) # 创建仅包含目标值的Categorical数组,提取第一个元素 cat_for_c1 = pd.Categorical(['c1'], dtype=cat_type)[0]
验证结果:
print(type(cat_for_c1)) # 输出 <class 'pandas._libs.cat.Categorical'> print(cat_for_c1) # 输出 c1
方法2:封装为工具函数(适合频繁调用)
def get_category(dtype, value): return pd.Categorical([value], dtype=dtype)[0] # 使用示例 cat_for_c2 = get_category(cat_type, 'c2')
额外提示:安全校验
如果要避免传入不在分类列表中的值导致生成NaN,可以添加校验逻辑:
def get_category_safe(dtype, value): if value not in dtype.categories: raise ValueError(f"值 {value} 不在当前分类列表中") return pd.Categorical([value], dtype=dtype)[0]
内容的提问来源于stack exchange,提问作者Michael Dorner
相关产品推荐
相关产品推荐

