Python:将xlrd表转换为numpy矩阵(ndarray)

vsdwdz23  于 2023-03-30  发布在  Python
关注(0)|答案(3)|浏览(243)

将成功加载的xlrd excel工作表转换为numpy矩阵(表示该工作表)的转换语法是什么?
现在,我正在尝试将电子表格的每一行添加到numpy矩阵中。我无法弄清楚将Sheet.row转换为numpy.ndarray的语法。以下是我到目前为止尝试的内容:

import xlrd
workbook = xlrd.open_workbook('input.xlsx')
worksheet = workbook.sheet_by_name('Sheet1')
num_rows = worksheet.nrows - 1
num_cells = worksheet.ncols - 1
inputData = numpy.empty([worksheet.nrows - 1, worksheet.ncols])
curr_row = -1
while curr_row < num_rows: # for each row
    curr_row += 1
    row = worksheet.row(curr_row)
    if curr_row > 0: # don't want the first row because those are labels
        inputData[curr_row - 1] = numpy.array(row)

我在最后一行尝试了各种方法,试图将行转换为numpy将接受的内容并添加到inputData矩阵中。正确的转换语法是什么?

wbgh16ku

wbgh16ku1#

我想知道你是否知道Pandas库,它具有xlsx加载功能:

import pandas as pd
df = pd.read_excel('input.xlsx')

您可以使用sheetname参数控制要读取的工作表,并且可以从values属性中的Pandas DataFrame获取Numpy数组。

oyt4ldly

oyt4ldly2#

你正在尝试将一个对象row,它是一个xlrd.sheet.Cell元素的列表,直接转换为一个numpy数组。这不会按照你想要的方式工作。你必须走很长的路,并且还要遍历每一列:

while curr_row < num_rows: # for each row
    curr_row += 1
    row = worksheet.row(curr_row)
    if curr_row > 0: # don't want the first row because those are labels
        for col_ind, el in enumerate(row):
            inputData[curr_row - 1, col_ind] = el.value

pandas中似乎有exist a function for this,正如建议的elsewhere on SO。Pandas Dataframe 继承自numpy数组,因此也可以转换为它们。可能最好不要重新发明轮子...

vngu2lb8

vngu2lb83#

要将xlrd工作表转换为numpy矩阵,我们需要迭代xlrd工作表。

import numpy
def to_numpy(book, sheet_no = 0):
    rows = book.sheet_by_index(sheet_no)
    return numpy.array([list(map(lambda x : x.value, rows.row(i))) for i in range(rows.nrows)])

arr = to_numpy(book, 0)

相关问题