首页 > 解决方案 > 如何读取动态大小的 Excel 文件?

问题描述

我不知道我是否表达了我的问题,但我会告诉你我想知道的。

我有一个带有多张工作表的 excel 文件。每个工作表具有相同的列数和不同的行数。我想阅读每个 excel 表并将其存储在 3D“项目”中(首先想到的是 MATLAB 单元格数组的等效形式)。在我使用这个单元格数组之后,我希望能够动态地遍历它。现在我已经编写了以下代码,其中我读取了 3D 数组中的表格(因此 excel 表格需要具有相同的尺寸):

excelF = pd.ExcelFile (fileName)
sheetsno = len(excelF.sheet_names)
dim = excelF.parse()
array = np.zeros((sheetsno,dim.shape[0],dim.shape[1]))
for i in range(0,sheetsno):
    df = pd.read_excel (fileName,sheet_name = i)
    array[i,:,:] = df.to_numpy()

标签: pythonexcelpandasdataframenumpy

解决方案


我已经测试了这段代码,它适用于具有多个维度的多张纸。我使用一个 python 列表并将一个 np 数组附加到每个工作表上的该列表。我不认为下一步是必要的(除非您想专门使用 numpy),但随后我将列表转换为 np.array

import pandas as pd
import numpy as np
excelF = pd.ExcelFile ('test.xlsx')
array = []
for i in range(0,len(excelF.sheet_names)):
    df = excelF.parse(i) # use excelF.parse(i,header=None) to include first row    
    array.append(df.to_numpy())
array = np.array(array)

推荐阅读