我正在使用二元分类数据集。我想将名义数据转换为数字。我该怎么办?
age | class
------------
1 | no
2 | yes
3 | no
4 | yes
5 | no
6 | no
7 | no
8 | yes
9 | no
10 | y
代码:
mapping = {label:idx for idx,label in enumerate(np.unique(['class']))}
df['class'] = df['class'].map(mapping)
所需输出:{'no':0 'yes':1}
最佳答案
您的代码的问题是这样的:
np.unique(['class'])
您正在尝试查找列表['class']
的唯一值,它只是一个值,您应该将其更改为:
np.unique(df['class'])
其中包含 class
列的所有不同值
但在此之前,您应该将噪声数据 y
替换为 yes
:
df['class'] = df['class'].replace('y', 'yes')
mapping
变量现在具有您想要的输出:
{'no':0 'yes':1}
完整代码:
import numpy as np
import pandas as pd
df = pd.DataFrame(['no', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'y'],columns=['class'])
df['class'] = df['class'].replace('y', 'yes') # replace your noisy data
mapping = {label:idx for idx,label in enumerate(np.unique(df['class']))} # make your mapping dict
df['class'] = df['class'].map(mapping) # map your class
关于python - 如何在python中将标称数据转换为数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67527277/