python - 如何在python中将标称数据转换为数值?

标签 python pandas data-mining enumerate data-preprocessing

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

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/

相关文章:

python - 如何创建另一列的部分重复?

r - R gbm 函数中的权重参数

data-mining - 数据挖掘中的异常值检测

python - 如何在 ../src/x86/ffi64.c :158 处修复 Python 函数 "classify_argument"中的段错误

python - Django-haystack 通用 SearchView - 无结果

python - 我应该如何对 1,100,000 行坐标信息进行地理定位?

python - 如何在python中将日期转换为纪元时间

machine-learning - 决策树——节点的熵可以为零吗?

python - py3k : Maximum Number In Given List - short form

python - 从时间戳中删除特定字符