本文介绍了将分类代码转换为分类值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框:
ga_deviceCategory_codes ga_channelgrouping_codes ga_sourceMedium_codes 1.0 6.0 9.0 1.0 6.0 9.0我已使用:从类别值转换为类别代码:
Which I have converted into categorical codes from categorical values using :
data['ga_deviceCategory_codes'] = data['ga_deviceCategory'].astype('category').cat.codes data['ga_channelgrouping_codes'] = data['ga_channelgrouping'].astype('category').cat.codes data['ga_sourceMedium_codes'] = data['ga_sourceMedium'].astype('category').cat.codes如何从上述代码中恢复到原始分类值?
How do I get back to the original categorical values now from the above codes?
推荐答案类别映射由Pandas内部存储,但不作为常规Python字典存储.您可以自己创建这样的字典以向后映射:
Category mappings are stored internally by Pandas, but not as a regular Python dictionary. You can create such a dictionary yourself to map backwards:
df['mycol'] = df['mycol'].astype('category') d = dict(enumerate(df['mycol'].cat.categories))然后向后映射:
df['mycol_codes'] = df['mycol'].cat.codes df['mycol_reversed'] = df['mycol_codes'].map(d)请谨慎使用此方法.确保转换为类别后立即创建字典.在将数据帧与分类序列串联时,您可能会发现映射更改.
Be careful with this method. Make sure you create the dictionary straight after you convert to categories. When concatenating dataframes with categorical series, you may find the mapping changes.
更多推荐
将分类代码转换为分类值
发布评论