使用 Python 对数据帧中的特征列表进行分类编码的 For 循环

问题描述

我想弄清楚如何编写一个 for 循环来对特征列表执行分类编码。

df = ['TRY','LOC','OUTPUT','TYPE_A','SIGNAL','A-B  SPOT']

目前,这就是我要做的,但似乎是重复的。

obj_df["TRY"] = obj_df["TRY"].astype('category')
obj_df["TRY_cat"] = obj_df["TRY"].cat.codes

我尝试按照示例编写它并尝试使用库,但我认为逻辑刚好。

根据我目前的处理方式,有没有办法做到这一点?理想情况下,我也想将其放入一个新的数据框中。

提前致谢!

解决方法

试试这个:

import pandas as pd
df = pd.DataFrame({'Color': {0: 'red',1: 'green',2: 'yellow',3: 'navy_blue'},'Shape': {0: 'square',1: 'circle',2: 'triangle',3: 'cube'},'Description': {0: 'happy',1: 'sad',2: 'mad',3: 'disgust'}})
cols = ['Color','Shape','Description']

df[cols] = df[cols].astype('category')
df[[col + '_cat' for col in cols]] = pd.concat([df[col].cat.codes for col in cols],axis=1)

print(df)
#        Color     Shape Description  Color_cat  Shape_cat  Description_cat
# 0        red    square       happy          2          2                1
# 1      green    circle         sad          0          0                3
# 2     yellow  triangle         mad          3          3                2
# 3  navy_blue      cube     disgust          1          1                0