Python数据预处理 - 文本数据的量化 - 代码实现

版权声明:转载请联系作者,获得允许后,添加链接及作者到页首 https://blog.csdn.net/weixin_40683253/article/details/81912027

在数据建模的过程中,很多变量都不是数字的,比如婚姻情况、性别、居住地等。这给建模本身造成了很大的干扰,因此在数据采集到数据建模的过程中,我们需要一个过程,叫量化。

比如这样一个源数据:

收入 身高 长相 体型 是否见面
一般
一般
一般
一般 一般 一般 一般
一般
一般
一般

下面是量化的过程,利用到了字典:

#coding:utf-8

import numpy as np
import pandas as pd
from pandas import DataFrame,Series

#读取文件
datafile = u'E:\\pythondata\\tree.xlsx'#文件所在位置,u为防止路径中有中文名称,此处没有,可以省略
data = pd.read_excel(datafile)#datafile是excel文件,所以用read_excel,如果是csv文件则用read_csv
print(data)
#将文本中不可直接使用的文本变量替换成数字
productDict={'高':1,'一般':2,'低':3, '帅':1,  '丑':3,  '胖':3,  '瘦':1,  '是':1,  '否':0}
data['income'] = data['收入'].map(productDict)#将每一列中的数据按照字典规定的转化成数字
data['hight'] = data['身高'].map(productDict)
data['look'] = data['长相'].map(productDict)
data['shape'] = data['体型'].map(productDict)
data['is_meet'] = data['是否见面'].map(productDict)
print(data.iloc[:,5:].as_matrix())#as_matrix()矩阵化

 运行结果:

[[2 1 3 3 0]
 [1 2 1 1 1]
 [1 2 1 1 1]
 [2 2 2 2 1]
 [1 1 3 2 0]
 [2 1 1 3 1]
 [3 3 2 1 0]
 [1 1 1 2 1]
 [1 1 1 1 0]
 [3 1 2 2 1]
 [1 3 1 3 1]
 [1 1 1 1 0]
 [1 1 1 2 1]
 [2 2 1 1 1]
 [1 1 1 2 1]
 [1 2 2 1 0]
 [3 1 1 2 0]
 [2 3 3 3 0]]

这是矩阵化之后的数据,便于各种建模,不需要矩阵化的话,就将最后一个print中的.as_matrix()去掉。

猜你喜欢

转载自blog.csdn.net/weixin_40683253/article/details/81912027