我想将工作簿中的 Excel 表格(使用 Excel 2007 及更高版本的制表功能制作)导入到单独的数据框中。如果之前有人问过这个问题,我深表歉意,但从我的搜索中我找不到我想要的东西。我知道你可以使用 read_excel 函数轻松地做到这一点,但是这个 requires the specification of a Sheetname或returns 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)
最佳答案
虽然不完全是我想要的,但我找到了一种获取表名称的方法,但需要注意的是它仅限于工作表名称。
以下是我当前使用的代码的摘录:
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
关于python - 将 Excel 表导入 pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54126858/