【问题标题】:Import Excel Tables into pandas dataframe将 Excel 表格导入熊猫数据框
【发布时间】:2019-06-05 05:09:44
【问题描述】:

我想将工作簿中的 Excel 表格(使用 Excel 2007 及更高版本的制表功能制作)导入单独的数据框。抱歉,如果之前有人问过这个问题,但从我的搜索中我找不到我想要的东西。我知道您可以使用 read_excel 函数轻松地做到这一点,但是这个 requires the specification of a Sheetnamereturns a dict of dataframes for each sheet

我想知道是否有一种方法可以指定表名,或者更好地为工作簿中的每个表返回一个数据框字典,而不是指定工作表名。

我知道这可以通过combining xlwings with pandas 完成,但想知道这是否已经内置在任何 pandas 函数中(可能是 ExcelFile)。

类似这样的:-

import pandas as pd
xls = pd.ExcelFile('excel_file_path.xls')
# to read all tables to a map
tables_to_df_map = {}
for table_name in xls.table_names:
    table_to_df_map[table_name] = xls.parse(table_name)

【问题讨论】:

  • 也许这回答了你的问题? stackoverflow.com/questions/26521266/…
  • @Manrique 感谢他的建议。我昨天发现了该帖子,但它仅与我不感兴趣的工作表加载相关。我对加载 Excel 表格感兴趣(使用转换为表格工具在 excel 中创建)。

标签: python excel pandas dataframe


【解决方案1】:

虽然不完全是我所追求的,但我找到了一种获取表名的方法,但需要注意的是它仅限于工作表名称。

这是我当前使用的代码的摘录:

import pandas as pd
import openpyxl as op
wb=op.load_workbook(file_location) 
# Connecting to the specified worksheet
ws = wb[sheetname]
# Initliasing an empty list where the excel tables will be imported
# into
var_tables = []
# Importing table details from excel: Table_Name and Sheet_Range
for table in ws._tables:
    sht_range = ws[table.ref]
    data_rows = []
    i = 0
    j = 0
    for row in sht_range:
        j += 1
        data_cols = []
        for cell in row:
            i += 1
            data_cols.append(cell.value)
            if (i == len(row)) & (j == 1):
                data_cols.append('Table_Name')
            elif i == len(row):
                data_cols.append(table.name)
        data_rows.append(data_cols)
        i = 0
    var_tables.append(data_rows)

# Creating an empty list where all the ifs will be appended
# into
var_df = []
# Appending each table extracted from excel into the list
for tb in var_tables:
    df = pd.DataFrame(tb[1:], columns=tb[0])
    var_df.append(df)
# Merging all in one big df
df = pd.concat(var_df,axis=1) # This merges on columns

【讨论】:

  • 它可能不是很pythonic,可以优化,但我没有花太多时间改进它。随时提出建议或改进:)
猜你喜欢
  • 1970-01-01
  • 2015-06-10
  • 2018-11-19
  • 1970-01-01
  • 2020-04-02
  • 2020-03-24
  • 2014-05-06
  • 2020-12-03
  • 1970-01-01
相关资源
最近更新 更多