python - 如何读取动态大小的 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()
解决方案
我已经测试了这段代码,它适用于具有多个维度的多张纸。我使用一个 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)
推荐阅读
- java - 如何从与给定状态关联的任务重新启动工作流
- vb.net - 随机化图像将进入的图片框
- python - 如何在 openCV 上获得 leptonica 的 pixReduceRankBinary2 和 pixCloseBrick 的相同结果?
- kivy - AttributeError:“Programa”对象没有属性“root”
- git - 从一个功能分支到另一个功能分支进行更改
- pandas - 如何使用 pandas 绘制堆积条形图
- javascript - 非异步 javascript 函数竞争条件
- openmp - openmp:for循环和临界区中的竞争条件
- json - 使用 PowerShell 如何替换并保存具有注释的 json 文件中的值
- mongodb - mongodb snappy 压缩数据大小与存储大小