将分类代码转换为分类值

编程入门 行业动态 更新时间:2024-10-26 10:29:20
本文介绍了将分类代码转换为分类值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个数据框:

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.

更多推荐

将分类代码转换为分类值

本文发布于:2023-10-27 03:43:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1532208.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!