Python数据预处理 - 将excel文件读入矩阵matrix中

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

机器学习中,很多算法的计算逻辑是基于数学的,免不了求特征值和特征向量这种事情,因此,在数据预处理的时候,将数据源中的数据转储成矩阵格式是很有必要的。

import numpy as np
import pandas as pd
from sklearn import preprocessing

def excel_to_matrix(path):
    table = xlrd.open_workbook(path).sheets()[0]#获取第一个sheet表
    row = table.nrows  # 行数
    col = table.ncols  # 列数
    datamatrix = np.zeros((row, col))#生成一个nrows行ncols列,且元素均为0的初始矩阵
    for x in range(col):
        cols = np.matrix(table.col_values(x))  # 把list转换为矩阵进行矩阵操作
        datamatrix[:, x] = cols # 按列把数据存进矩阵中
    #数据归一化   
    min_max_scaler = preprocessing.MinMaxScaler()
    datamatrix  = min_max_scaler.fit_transform(datamatrix)
    return datamatrix

datafile = u'E:\\pythondata\\test.xlsx'
excel_to_matrix(datafile)

运行结果:

array([[1.        , 0.13209733, 1.        ],
       [0.43478261, 0.16917729, 0.26420934],
       [0.5942029 , 0.87949015, 0.4372538 ],
       [0.60869565, 0.50405562, 0.        ],
       [0.11594203, 1.        , 0.51547552],
       [0.        , 0.        , 0.87070906]])

代码中min_max_scaler = preprocessing.MinMaxScaler()是做数据归一化用的,MinMaxScaler()默认将数据归一到  [0, 1],这是比较常用的,但是也有一些时候是归一到 [-1, 1],有时候是需要做数据标准化,而这些东西都在另外一篇文章中说过了,下面是链接,参考着学习吧,一起成长!

Python数据预处理 - 归一化与标准化

猜你喜欢

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