Pandas - 从Excel读取表格

3
我正在尝试用Pandas从Excel中读取一个表格,但是我无法做到。
例如,下面的代码适用于我,并且它可以读取来自File.xlsx文件上的Sheet1中的数据。
df = pd.read_excel('File.xlsx', sheetname='Sheet1')

但是在那个表格中有一个名为“Table4”的表格,我想使用Python在pandas中读取它。

The table looks like

这段文字的翻译如下:

表格可以按行或列增加。只有表格名称不变。表格的侧边内容也会发生变化。

您可以使用Pandas来实现这一点,或者您可以建议其他替代方案。


1
你能分享一张包含表格的Excel截图吗? - meW
你正在使用的pandas版本是什么? - Mayank Porwal
@MayankPorwal 0.19.2 - - Student of the Digital World
@meW 已添加。谢谢。 - Student of the Digital World
据我所知,没有读取特定对象的选项。解决方法总是先读取整个对象,然后相应地进行切片。 - Yuca
@Sid29 我相信在 pandas 版本 0.22 及以上,此问题已得到解决。请尝试升级 pandas 版本。它应该能够轻松读取表格。 - Mayank Porwal
2个回答

5

Pandas目前没有直接读取表格的方法,但是下面这个函数可以使用openpyxl库来读取(这也是pandas用于读取当前excel文件的库)。

请注意,这种技术是从我未撰写的博客文章(在此处找到)中学到的,尽管我的代码略有不同。

import pandas as pd
import openpyxl

def read_table(file_name: str, table_name: str) -> pd.DataFrame:
    wb = openpyxl.load_workbook(file_name, read_only= False, data_only = True) # openpyxl does not have table info if read_only is True; data_only means any functions will pull the last saved value instead of the formula
    for sheetname in wb.sheetnames: # pulls as strings
        sheet = wb[sheetname] # get the sheet object instead of string
        if table_name in sheet.tables: # tables are stored within sheets, not within the workbook, although table names are unique in a workbook
            tbl = sheet.tables[table_name] # get table object instead of string
            tbl_range = tbl.ref #something like 'C4:F9'
            break # we've got our table, bail from for-loop
    data = sheet[tbl_range] # returns a tuple that contains rows, where each row is a tuple containing cells
    content = [[cell.value for cell in row] for row in data] # loop through those row/cell tuples
    header = content[0] # first row is column headers
    rest = content[1:] # every row that isn't the first is data
    df = pd.DataFrame(rest, columns = header)
    wb.close()
    return df

版本:

In [50]: pd.__version__
Out[50]: '1.3.5'

In [51]: openpyxl.__version__
Out[51]: '3.0.9'

谢谢您。这个话题的信噪比非常可怕,尤其是对于本应该从一开始就在pandas.read_excel中处理的事情来说。 - Ian Beyer

0
正如@MayankPorwal建议的那样,升级pandas版本。我目前正在使用0.23.4版本,并且可以轻松地加载如下表格。
pd.__version__
0.23.4

输入 Excel 文件 -

input

读取代码 -

df = pd.read_excel('SO.xlsx')
df

输出 -

output


那就是了。我只需要Column1、Column2和Column3以及它下面的三行。它在Excel中被定义为Table 4对象,我只需要这个。 - Student of the Digital World
一旦您完整加载了Excel,您可以轻松地索引表格,或者您有其他限制吗? - meW
它可以动态地改变列名和周围的数据。 - Student of the Digital World
你能告诉我列名是否遵循任何模式,例如 ColA,ColB,ColC。此外,您是否知道表中的行数? - meW
思考一下,我会在这件事上回复你的。 - Student of the Digital World

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接