首页 > 解决方案 > 如何使用python在excel表格中提取不同的表格

问题描述

在一个 excel 文件中,工作表 1,工作表的不同位置有 4 个表格。如何读取这 4 个表格。例如,我什至从谷歌添加了一张图片快照以供参考。不使用索引还有其他方法可以提取表。

在此处输入图像描述

标签: python-3.xexcelpandasdataframe

解决方案


我假设您的表格格式为“ Excel 表格”。您可以通过标记一个范围来创建一个 Excel 表格,然后单击:

在此处输入图像描述

然后有一个来自 Samuel Oranyeli 的很好的指南,如何使用 Python 导入 Excel 表格。我使用了他的代码并举例说明。


我在 excel 中使用了以下数据,其中每种颜色代表一个表格。

在此处输入图像描述


关于代码的备注:

以下部分可用于检查我们正在使用的工作表中存在哪些表:

# check what tables that exist in the worksheet
print({key : value for key, value in ws.tables.items()})

在我们的示例中,此代码将给出:

{'Table2': 'A1:C18', 'Table3': 'D1:F18', 'Table4': 'G1:I18', 'Table5': 'J1:K18'}

在这里设置数据框名称。如果数据帧的数量与表的数量不匹配,请务必小心,您将收到错误消息。

# Extract all the tables to individually dataframes from the dictionary
Table2, Table3, Table4, Table5 = mapping.values()

# Print each dataframe
print(Table2.head(3)) # Print first 3 rows from df

print(Table2.head(3))给出:

   Index   first_name   last_name     address
   0          Aleshia   Tomkiewicz    14 Taylor St
   1             Evan   Zigomalas     5 Binney St
   2           France   Andrade       8 Moor Place

完整代码:

#import libraries
from openpyxl import load_workbook
import pandas as pd

# read file
wb = load_workbook("G:/Till/Tables.xlsx") # Set the filepath + filename

# select the sheet where tables are located
ws = wb["Tables"]

# check what tables that exist in the worksheet
print({key : value for key, value in ws.tables.items()})

mapping = {}

# loop through all the tables and add to a dictionary
for entry, data_boundary in ws.tables.items():
    # parse the data within the ref boundary
    data = ws[data_boundary]
    
    ### extract the data ###
    # the inner list comprehension gets the values for each cell in the table
    content = [[cell.value for cell in ent] 
               for ent in data]
    
    header = content[0]
    
    #the contents ... excluding the header
    rest = content[1:]
    
    #create dataframe with the column names
    #and pair table name with dataframe
    df = pd.DataFrame(rest, columns = header)
    mapping[entry] = df

#  print(mapping)

# Extract all the tables to individually dataframes from the dictionary
Table2, Table3, Table4, Table5 = mapping.values()

# Print each dataframe
print(Table2)
print(Table3)
print(Table4)
print(Table5)

示例数据,示例文件

地址 城市 邮政
阿莱希亚 汤姆凯维奇 14 泰勒街 圣斯蒂芬斯病房 肯特 CT2 7PP
埃文 齐戈马拉斯 5宾尼街 修道院病房 白金汉郡 HP11 2AX
法国 安德拉德 8 摩尔广场 东南本和塔克顿 W 伯恩茅斯 BH6 3BE
尤利西斯 麦克沃尔特斯 埃克塞特路 505 号 Hawerby 暨 Beesby 林肯郡 DN36 5RP
泰莎 维内斯 福斯街 5396 号 问候格林和林格沃德 西米德兰兹郡 B70 9DT
埃里克 脾气暴躁 林德街 9472 号 德斯伯勒 北安普敦郡 NN14 2GH
玛格 格拉斯米克 7457 考尔街 #70 巴盖特沃德 南安普敦 SO14 3TY
拉基塔 希索 20 格洛斯特 Pl #96 奇顿病房 泰恩威尔 NE29 7AD
卢拉 曼泽拉 奥古斯丁街 929 号 斯台普希尔病房 南格洛斯特郡 BS16 4LL
悦特 克拉佩克 45 布拉德菲尔德街 #166 帕维奇 德比郡 DE6 1QN
费尔南达 作家 北安普顿街 620 号 威尔明顿 肯特 DA2 7PP
查尔斯塔 厄姆 海吉亚街 5 号 朗兹利格林沃德 德比郡 S40 4LY
科琳 贾雷特 莫利街 2150 号 迪沃德 邓弗里斯和加洛韦 DG8 7DE
涅沙 布鲁赫 24 博尔顿街 Broxburn、Uphall 和 Winchburg 西洛锡安 EH52 5TL
鲁本 肠杆菌属 4福雷斯特街 韦斯顿超级母马 北萨默塞特 BS23 3HG
米歇尔 特罗塞尔 89 中午街 卡布鲁克 诺福克 IP25 6JQ
埃德加 坎内 格思里街 99 号 新米尔顿 汉普郡 BH25 5DF

推荐阅读