python - 在 python 中的数据帧上应用一种热编码
问题描述
我正在处理一个数据集,其中我有各种不同值的字符串列,并且想要应用one hot encoding
.
这是示例数据集:
v_4 v5 s_5 vt_5 ex_5 pfv pfv_cat
0-50 StoreSale Clothes 8-Apr above 100 FatimaStore Shoes
0-50 StoreSale Clothes 8-Apr 0-50 DiscountWorld Clothes
51-100 CleanShop Clothes 4-Dec 51-100 BetterUncle Shoes
所以,在这里我需要应用一个热编码,pvf_cat
就像我有其他列一样,我已经创建了这些列的列表,这str_cols
就是我应用的方式one-hot-encoding
:
for col in str_cols:
data = df[str(col)]
values = list(data)
# print(values)
# integer encode
label_encoder = LabelEncoder()
integer_encoded = label_encoder.fit_transform(values)
print(integer_encoded)
# one hot encode
encoded = to_categorical(integer_encoded)
print(encoded)
# invert encoding
inverted = argmax(encoded[0])
print(inverted)
onehot_encoder = OneHotEncoder(sparse=False)
integer_encoded = integer_encoded.reshape(len(integer_encoded), 1)
onehot_encoded = onehot_encoder.fit_transform(integer_encoded)
但它不影响数据集,当我打印它时df.head()
它仍然是一样的,这里有什么问题?
解决方案
使用pd.get_dummies()
比为此编写自己的代码要容易得多,而且可能也更快。
df = pd.get_dummies(df, columns=['pfv_cat'])
v_4 v5 s_5 vt_5 ex_5 pfv pfv_cat_Clothes pfv_cat_Shoes
0 0-50 StoreSale Clothes 8-apr above 100 FatimaStore 0 1
1 0-50 StoreSale Clothes 8-apr 0-50 DiscountWorld 1 0
2 51-100 CleanShop Clothes 4-dec 51-100 BetterUncle 0 1
在columns=
参数后面的列表中,您可以指定要 OneHotEncoded 的列。所以在你的情况下,这可能是df = pd.get_dummies(df, columns=str_cols)
.
推荐阅读
- javascript - 如何将输入值写入 PHP 中的文件?
- arrays - 在 C 编程中打印数组的元素
- asp.net-core - 防止包含跨域脚本-asp.net core 5.0 中的自我 XSS
- string - 使用选择字符串从 1000 多个文件中输出列表
- python - 获取 dir() 的简洁版本
- javascript - 如何更改嵌套标记行中外部标记的 innerText?
- vba - 删除所有使用已知密码锁定的 Word 宏
- reactjs - 在单个 spa microfrond end root-config 中添加反应组件
- python - 根据数据框中其他列数据的计算创建新列
- azure - 为什么 Azure Chatbot Session 在网站上部署时会出现问题?聊天机器人没有响应