编程语言
首页 > 编程语言> > python – 如何知道由astype(‘category’)指定的标签.cat.codes?

python – 如何知道由astype(‘category’)指定的标签.cat.codes?

作者:互联网

我有以下数据框称为语言

         lang          level
0      english         intermediate
1      spanish         intermediate
2      spanish         basic
3      english         basic
4      english         advanced
5      spanish         intermediate
6      spanish         basic
7      spanish         advanced

我通过使用将每个变量分类为数字

language.lang.astype( ‘类别’).cat.codes

language.level.astype( ‘类别’).cat.codes

分别.获取以下数据框:

      lang   level
0      0       1
1      1       1
2      1       0
3      0       0
4      0       2
5      1       1
6      1       0
7      1       2

现在,我想知道是否有办法获得哪个原始值对应于每个值.我想知道lang列中的0值对应于英语,依此类推.

是否有任何功能可以让我收回这些信息?

解决方法:

你可以生成字典:

c = language.lang.astype('category')

d = dict(enumerate(c.cat.categories))
print (d)
{0: 'english', 1: 'spanish'}

那么如果有必要可以映射:

language['code'] = language.lang.astype('category').cat.codes

language['level_back'] = language['code'].map(d)
print (language)
      lang         level  code level_back
0  english  intermediate     0    english
1  spanish  intermediate     1    spanish
2  spanish         basic     1    spanish
3  english         basic     0    english
4  english      advanced     0    english
5  spanish  intermediate     1    spanish
6  spanish         basic     1    spanish
7  spanish      advanced     1    spanish

标签:categorical-data,python,pandas,dataframe
来源: https://codeday.me/bug/20190910/1801845.html