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

Python: Convert xlrd sheet to numpy matrix (ndarray)

将成功加载的 xlrd excel sheet 转换为 numpy 矩阵(表示 sheet)的转换语法是什么?

现在我正在尝试获取分布的每一行sheet并将其添加到 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 矩阵的内容。正确的转换语法是什么?

您正在尝试将对象 row 直接转换为 numpy 数组,该对象是 xlrd.sheet.Cell 元素的列表。这不会按照你想要的方式工作。您必须从头到尾执行此操作,还要遍历每一列:

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

好像有exist a function for this in pandas though, as suggested elsewhere on SO。 pandas 数据帧继承自 numpy 数组,因此也可以转换为它们。也许最好不要重新发明轮子...

我想知道您是否知道 Pandas 具有 xlsx 加载功能的库:

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

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