python对离散变量的one-hot编码方法
我们在进行建模时,变量中经常会有一些变量为离散型变量,例如性别。这些变量我们一般无法直接放到模型中去训练模型。因此在使用之前,我们往往会对此类变量进行处理。一般是对离散变量进行one-hot编码。下面具体介绍通过python对离散变量进行one-hot的方法。
注意:这里提供两种哑编码的实现方法,pandas和sklearn。它们最大的区别是,pandas默认只处理字符串类别变量,sklearn默认只处理数值型类别变量(需要先 LabelEncoder )
① pd.get_dummies(prefix=)
pandas的get_dummies()可以直接对变量进行one-hot编码,其中prefix是为one-hot编码后的变量进行命名。
②LabelEncoder和OneHotEncoder
我们也可以通过sklearn的模块实现对离散变量的one-hot编码,其中LabelEncoder是将离散变量替换为数字,
OneHotEncoder则实现对替换为数字的离散变量进行one-hot编码。
注:get_dummies()可以直接对字符型变量进行one-hot编码,但OneHotEncoder不能直接对字符型变量编码,因此我们需要先将字符型变量转换为数值型变量。这就是为什么在OneHotEncoder之前需要LabelEncoder的原因。
下面我们通过实例来介绍这两种方法的具体使用:
①数据的导入
import pandas as pd import os os.getcwd() os.chdir('E:\study\kaggle\Titanic') from sklearn.preprocessing import OneHotEncoder from sklearn.preprocessing import LabelEncoder data = pd.read_csv('train.csv')
②数据熟悉
data['Sex'].value_counts() Out[38]: male 577 female 314 Name: Sex, dtype: int64 #可以看到,变量Sex为字符型变量,取值有male和female两种
③get_dummies
Sex_ohe_1 = pd.get_dummies(data['Sex']) Sex_ohe_1.head() Out[40]: female male 0 0 1 1 1 0 2 1 0 3 1 0 4 0 1
④OneHotEncoder
Sex_ohe_2 = OneHotEncoder(sparse=False).fit_transform(data['Sex'].reshape((-1,1))) ValueError: could not convert string to float: male
可以看到OneHotEncoder无法直接对字符型变量进行编码,需要通过OneHotEncoder将字符型变量转换为数值型变量。
le_sex=LabelEncoder().fit(data['Sex']) Sex_label=le_sex.transform(data['Sex']) Sex_label= LabelEncoder().fit_transform(data['Sex']) #fit_transform等价于fit和transform两个函数结合 ohe_sex=OneHotEncoder(sparse=False).fit(Sex_label.reshape(-1,1)) Sex_ohe=ohe_sex.transform(Sex_label.reshape(-1,1)) Sex_ohe_3 = OneHotEncoder(sparse=False).fit_transform(Sex_label.reshape((-1,1)))
注:get_dummies返回的为数据框,OneHotEncoder返回的为数组。
以上这篇python对离散变量的one-hot编码方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
- python对离散变量的one-hot编码
- python的scikit-learn将特征转成one-hot特征的方法
- 解决yum升级的问题“There was a problem importing one of the Python modules”
- 对python 数据处理中的LabelEncoder 和 OneHotEncoder详解
- [Python]Processing a String One Character at a Time
- Recipe 1.1. Processing a String One Character at a Time(Python Cookbook)
- Python: keep strings in double quote as one word when split string to words
- 数据预处理练习 等频分箱、one_hot(独热编码)、数据归一化 #python
- python diary ONE
- 对python sklearn one-hot编码详解
- one-line conditional & switch statements in python
- Python3 爬虫实战(一)——爬取one每日一句,并保存到本地
- one difference of python3 from python
- Python: Catch multiple exceptions in one line (except block)
- python-django的many to one模型
- [LeetCode]Plus One@python
- Replace multiple spaces with one space in Python(替换多个空格为一个空格)
- python 数据处理中的 LabelEncoder 和 OneHotEncoder
- Computing the Relative Path from One Directory to Another(Python cookbook 2-22)
- python-层次聚类-离散变量