基于pandas将类别属性转化为数值属性的方法
作者:chenpe32cp 时间:2021-11-24 07:15:16
离散特征的编码分为两种情况:
1、离散特征的取值之间没有大小的意义,比如color:[red,blue],那么就使用one-hot编码
2、离散特征的取值有大小的意义,比如size:[X,XL,XXL],那么就使用数值的映射{X:1,XL:2,XXL:3}
使用pandas可以很方便的对离散型特征进行one-hot编码
import pandas as pd
df = pd.DataFrame([
['green', 'M', 10.1, 'class1'],
['red', 'L', 13.5, 'class2'],
['blue', 'XL', 15.3, 'class1']])
df.columns = ['color', 'size', 'prize', 'class label']
size_mapping = {
'XL': 3,
'L': 2,
'M': 1}
df['size'] = df['size'].map(size_mapping)
class_mapping = {label:idx for idx,label in enumerate(set(df['class label']))}
df['class label'] = df['class label'].map(class_mapping)
说明:对于有大小意义的离散特征,直接使用映射就可以了,{‘XL':3,'L':2,'M':1 }
Using the get_dummies will create a new column for every unique string in a certain column:使用get_dummies进行one-hot
编码
pd.get_dummies(df)
来源:https://blog.csdn.net/chenpe32cp/article/details/75452592
标签:pandas,数值,属性
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python MOCK SERVER moco模拟接口测试过程解析
2023-12-15 06:37:00
![](https://img.aspxhome.com/file/2023/0/101210_0s.png)
手把手带你了解Python数据分析--matplotlib
2022-05-21 22:07:18
![](https://img.aspxhome.com/file/2023/4/87654_0s.png)
Python Dataframe 指定多列去重、求差集的方法
2022-01-12 00:40:19
python3 mmh3安装及使用方法
2021-08-02 00:31:05
![](https://img.aspxhome.com/file/2023/7/79567_0s.png)
DIV与Table布局在大型网站的可用性比较
2007-10-08 12:46:00
![](https://img.aspxhome.com/file/UploadPic/200710/8/2007108125233616s.jpg)
Python远程开发环境部署与调试过程图解
2023-06-07 08:10:40
![](https://img.aspxhome.com/file/2023/9/72199_0s.png)
CSS 的模块化思想
2009-02-03 12:52:00
利用Python实现多种风格的照片处理
2021-05-04 13:26:27
![](https://img.aspxhome.com/file/2023/9/127659_0s.gif)
详解Python中__str__和__repr__方法的区别
2023-02-28 17:29:17
MySQL数据库中对前端和后台进行系统优化
2009-01-04 13:39:00
优雅管理Go Project生命周期
2023-06-16 01:10:42
![](https://img.aspxhome.com/file/2023/0/87630_0s.jpg)
SQL Server数据在不同数据库中的应用
2008-12-24 15:34:00
Python实现滑动平均(Moving Average)的例子
2023-02-10 22:36:58
python中利用Future对象回调别的函数示例代码
2021-09-28 13:03:43
表单制作方式大比拼
2008-10-09 11:32:00
![](https://img.aspxhome.com/file/uploadpic/20071/2007131102013522.gif)
python用字典统计单词或汉字词个数示例
2021-09-02 17:14:10
Python Pandas 如何shuffle(打乱)数据
2023-04-22 23:17:16
![](https://img.aspxhome.com/file/2023/5/95855_0s.png)
django 邮件发送模块smtp使用详解
2021-09-24 23:04:15
termux中matplotlib无法显示中文问题的解决方法
2022-12-16 00:07:16
![](https://img.aspxhome.com/file/2023/6/128516_0s.png)
JavaScript中创建原子的方法总结
2023-06-29 12:22:14