pandas 中对特征进行硬编码和onehot编码的实现
作者:很吵请安青争 时间:2021-03-26 22:37:49
首先介绍两种编码方式硬编码和onehot编码,在模型训练所需要数据中,特征要么为连续,要么为离散特征,对于那些值为非数字的离散特征,我们要么对他们进行硬编码,要么进行onehot编码,转化为模型可以用于训练的特征
初始化一个DataFrame
import pandas as pd
df = pd.DataFrame([
['green', 'M', 20, 'class1'],
['red', 'L', 21, 'class2'],
['blue', 'XL',30, 'class3']])
df.columns = ['color', 'size', 'weight', 'class label']
硬编码:
将feature的值从0(或者1)开始进行连续编码,比如color进行硬编码,color的值有三个,分别为编码为1,2,3
可以用如下操作,对color字段下的值进行硬编码
colorMap = {elem:index+1 for index,elem in enumerate(set(df["color"]))}
df['color'] = df['color'].map(colorMap)
这样可以进行硬编码了,之前我的写法是,先生成map,然后对每一行进行apply,显然没有上述代码简便
onehot编码:
将某个字段下所有值横向展开,对于每条数据,其在对应展开的值上的值就是1,听起来比较绕口,看下面的例子就知道了,python中,pandas 用get_dummies()方法即可
data1 = pd.get_dummies(df[["color"]])
如果要对多个feature 进行onehot,这样即可df[[fea1,fea2..]]
对于onehot以后的数据,如果需要原有的数据合并,直接拿原来的join onehot的数据即可
res = df.join(data1)
join操作默认是根据index来进行join的,而get_dummies()不会改变index
来源:https://blog.csdn.net/dpengwang/article/details/84838688
标签:pandas,硬编码,onehot编码
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python判断、获取一张图片主色调的2个实例
2022-07-26 18:27:00
python爬虫 正则表达式使用技巧及爬取个人博客的实例讲解
2023-11-06 02:16:54
![](https://img.aspxhome.com/file/2023/0/67800_0s.jpg)
python装饰器代替set get方法实例
2023-01-25 15:40:37
PHP中quotemeta()函数的用法讲解
2023-06-08 04:04:24
![](https://img.aspxhome.com/file/2023/7/55377_0s.png)
Linux 中PHP的安装教程
2023-10-07 20:34:21
在python中按照特定顺序访问字典的方法详解
2023-02-09 07:14:34
Pandas实现聚合运算agg()的示例代码
2023-09-27 12:35:49
![](https://img.aspxhome.com/file/2023/2/86162_0s.png)
Python3.5面向对象编程图文与实例详解
2023-12-04 23:21:51
![](https://img.aspxhome.com/file/2023/8/88008_0s.png)
tensorflow使用指定gpu的方法
2022-10-23 16:00:31
详解python的异常捕获
2023-05-27 11:24:03
![](https://img.aspxhome.com/file/2023/7/71517_0s.png)
response.getWriter().write()向前台打印信息乱码问题解决
2023-07-05 05:29:37
Mysql入门系列:MySQL数据目录的位置
2008-11-24 12:59:00
![](https://img.aspxhome.com/file/UploadPic/200811/20081129183226513.jpg)
Python xpath表达式如何实现数据处理
2021-09-02 22:07:15
常见数据库系统比较 Oracle数据库
2010-07-28 12:44:00
Python利用Turtle绘制Technoblade的示例代码
2023-08-23 22:43:01
![](https://img.aspxhome.com/file/2023/0/62260_0s.png)
python 密码加密与解密的实现
2023-07-31 04:32:38
![](https://img.aspxhome.com/file/2023/3/61433_0s.png)
document.all与WEB标准
2008-03-16 14:28:00
最炫Python烟花代码全解析
2022-02-16 13:07:53
![](https://img.aspxhome.com/file/2023/0/85030_0s.jpg)
SQL Server 2008中有关XML的新功能
2008-06-04 12:57:00
Python CSV模块使用实例
2022-02-04 18:56:36