python - 在一列上安装 one-hot 编码器并适用于许多
问题描述
我有一个包含两个分类列的数据框,包含相同的字符串集,我想对其进行一次热编码。列可以包含的字符串集是确定的,并且单热编码必须在两列之间保持一致。两列都包含所有可能的值,甚至多次。
在下面的示例中,我将编码器安装在包含列可以包含的字符串集的列表中。然后转换数据框的列。
问题1:这有意义吗?
问题2:如何对两列的one-hot编码返回的列有不同的名称?现在,我可以将列放入数据报中,但它们的名称相同。这是个问题,对吧?如何避免?
#list of values
all_stuff = ['Boat','Bike']
#create dataframe
data = {'Stuff': ['Bike', 'Boat'], 'More Stuff': ['Boat', 'Bike']}
index = range(len(data['Stuff']))
columns = ['Stuff','More Stuff']
df = pd.DataFrame(data, index=index, columns=columns)
df
#label encoder
label_encoder = LabelEncoder()
label_encoder.fit(all_stuff)
df['Stuff'] = label_encoder.transform(df['Stuff'])
df
df['More Stuff'] = label_encoder.transform(df['More Stuff'])
df
#one-hot encoding on first column (fit and transform)
enc = OneHotEncoder(handle_unknown='ignore')
stuff_cols = enc.fit(df['Stuff'].values.reshape(-1, 1))
stuff_cols = enc.transform(df['Stuff'].values.reshape(-1, 1)).toarray()
stuff_cols
df = pd.concat([df, pd.DataFrame(stuff_cols, columns=enc.get_feature_names())], axis=1)
df
#one hot enc on second column (ONLY tranform)
more_stuff_cols = enc.transform(df['More Stuff'].values.reshape(-1, 1)).toarray()
more_stuff_cols
df = pd.concat([df, pd.DataFrame(more_stuff_cols, columns=enc.get_feature_names())], axis=1)
df
#the column nales are the same!!
解决方案
我认为您可以为此使用 pandasget_dummies
功能:
df = pd.DataFrame({'Stuff': ['Bike', 'Boat'], 'More Stuff': ['Boat', 'Bike']})
pd.get_dummies(df)
输出:
Stuff_Bike Stuff_Boat More Stuff_Bike More Stuff_Boat
0 1 0 0 1
1 0 1 1 0