使用cat.codes时如何找出数字标签对应的内容? (将猫的专长转换为数值后)

问题描述 投票:0回答:1

我正在开发一个 ML 项目,并正在做一些初步的特征选择(当我稍后训练我的实际机器学习模型时,我打算使用 OneHotEncoding)。

为了进行特征选择,我需要将分类变量转换为数字代码,例如女性:0,男性:1,其他:2。我无法手动完成,因为我有太多的功能和值。我正在尝试使用 cat.codes 但我无法让它告诉我该值对应的内容。例如。 0 对应的是男性、女性还是其他?

我尝试了2种方法,但似乎都不起作用

#Example data
import pandas as pd
data = [[14, "Male", "employed"], [89, "Female", "student"], [48, "Other", "employed"]]
df = pd.DataFrame(data, columns=['Age', 'Gender', 'Occupation'])

#Convert categorical feats to numeric values
categorical_feat = ["Gender", "Occupation"]
for col in categorical_feat:
    df[col] = df[col].astype("category").cat.codes

#Trying to find out what the numeric values correspond to:
df["Gender"].cat.categories[0]   #AttributeError: Can only use .cat accessor with a 'category' dtype
df["Gender"].astype("category").cat.categories[0]    #output is 0 ....which isnt what I want. I'm expecting "male" or "female" or "other"

python pandas preprocessor
1个回答
0
投票

这是您可能可以适应的一种方法:

categorical_feat = ["Gender", "Occupation"]
for col in categorical_feat:
    df[col] = df[col].astype("category")
    print(dict( enumerate(df[col].cat.categories )))
    df[col] = df[col].cat.codes
    
print(df)

给出:

{0: 'Female', 1: 'Male', 2: 'Other'}
{0: 'employed', 1: 'student'}

   Age  Gender  Occupation
0   14       1           0
1   89       0           1
2   48       2           0
© www.soinside.com 2019 - 2024. All rights reserved.