2

我正在使用二进制分类数据集。我想将名义数据转换为数字。我该怎么办?

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}

4

1 回答 1

0

您的代码的问题是:

np.unique(['class'])

您正在尝试查找 list 的唯一值['class'],这只是一个值,您应该将其更改为:

np.unique(df['class'])

它具有class列的所有不同值

但在此之前,您应该将嘈杂的数据替换yyes

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
于 2021-05-13T23:20:41.970 回答