python讀Excel數據成numpy數組


        今年研究生數模的時候用到了,113.xlsx 是325個樣本數據,每個樣本數據126個初步篩選的特征

@

按列讀

import xlrd
import numpy as np

def excel2matrix(path):
    data = xlrd.open_workbook(path)
    table = data.sheets()[0]
    nrows = table.nrows  # 行數
    ncols = table.ncols  # 列數
    datamatrix = np.zeros((nrows, ncols))
    for i in range(ncols):
        cols = table.col_values(i)
        datamatrix[:, i] = cols
    return datamatrix

pathX = '113.xlsx'  #  113.xlsx 在當前文件夾下
x = excel2matrix(pathX)
print(x)
print(x.shape)

輸出

[[0.01719892 0.86457238 0.01742387 ... 1. 1. 0.9999603 ]
[0.0319469 0.86909879 0.01730402 ... 0.99351703 0.99445369 0.99997023]
[0.02805216 0.87040528 0.01724861 ... 0.99051946 0.99251572 0.99993467]
...
[0.63507299 0.03643383 0.99306191 ... 0.03441377 0.01650907 0.00848835]
[0.64464586 0.05750134 0.99653096 ... 0.03317541 0.01337929 0.00424418]
[0.64765852 0.09031475 1. ... 0.03193705 0.01024951 0. ]]
 
(325, 126)

簡單,但是很有用的一個小東西

按行讀

當然你可以按行讀

import xlrd
import numpy as np

def excel2matrix(path):
    data = xlrd.open_workbook(path)
    table = data.sheets()[0]
    nrows = table.nrows  # 行數
    ncols = table.ncols  # 列數
    datamatrix = np.zeros((nrows, ncols))
    for i in range(nrows):
        rows = table.row_values(i)
        datamatrix[i,:] = rows
    return datamatrix

pathX = '113.xlsx'  #  113.xlsx 在當前文件夾下
x = excel2matrix(pathX)
print(x)
print(x.shape)

輸出

[[0.01719892 0.86457238 0.01742387 ... 1. 1. 0.9999603 ]
[0.0319469 0.86909879 0.01730402 ... 0.99351703 0.99445369 0.99997023]
[0.02805216 0.87040528 0.01724861 ... 0.99051946 0.99251572 0.99993467]
...
[0.63507299 0.03643383 0.99306191 ... 0.03441377 0.01650907 0.00848835]
[0.64464586 0.05750134 0.99653096 ... 0.03317541 0.01337929 0.00424418]
[0.64765852 0.09031475 1. ... 0.03193705 0.01024951 0. ]]
 
(325, 126)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM