python实现哑变量编码
时间: 2024-01-09 14:05:18 浏览: 111
哑变量编码是一种将分类变量转换为数值变量的方法。在Python中,可以使用pandas库的get_dummies函数来实现哑变量编码。
下面是一个例子,假设有一个数据集包含性别和职业两个分类变量:
```
import pandas as pd
data = {'Gender': ['Male', 'Female', 'Male', 'Male', 'Female'],
'Occupation': ['Engineer', 'Teacher', 'Doctor', 'Lawyer', 'Doctor']}
df = pd.DataFrame(data)
print(df)
```
输出:
```
Gender Occupation
0 Male Engineer
1 Female Teacher
2 Male Doctor
3 Male Lawyer
4 Female Doctor
```
现在我们将使用get_dummies函数对这些分类变量进行哑变量编码:
```
encoded_df = pd.get_dummies(df, columns=['Gender', 'Occupation'])
print(encoded_df)
```
输出:
```
Gender_Female Gender_Male Occupation_Doctor Occupation_Engineer Occupation_Lawyer Occupation_Teacher
0 0 1 0 1 0 0
1 1 0 0 0 0 1
2 0 1 1 0 0 0
3 0 1 0 0 1 0
4 1 0 1 0 0 0
```
我们可以看到,每个分类变量都被转换为了多个数值变量,其中每个数值变量对应一个分类变量取值。这些数值变量被称为“哑变量”。在上面的输出中,Gender变量被转换为了Gender_Female和Gender_Male两个哑变量,Occupation变量被转换为了Occupation_Doctor、Occupation_Engineer、Occupation_Lawyer和Occupation_Teacher四个哑变量。
阅读全文