首页 > 解决方案 > 如何在不覆盖 Excel 中的第一行的情况下将标题添加到数据框(使用“.parse”从 excel 创建)

问题描述

我想从多个工作表和文件中读取多个 Excel 文件。最大的问题只是在工作表的生成数据框中添加一个标题(因为原始的 excel-Files 没有),因为所有使用的方法仍然覆盖第 1 行/第 1 行中的值(A1,B1 ... )。

目前的代码:

# before the path was declared 
xl = pd.ExcelFile(file)

# there is additional code above which reads all the files in a folder, selecting the relevant ones and open them
sheetHeader = ["A", "B", "C", "D", "E", "F", "G", "H"]

# rotation through all excel-sheets starts 
for sheetNames in xl.sheet_names:
     df_sheetExtraction = xl.parse(sheet_names = sheetNames, 
                                   header = 0, 
                                   names = sheetHeader)

     #example for asking at the specific cell value
     if df_sheetExtraction["B"][1] == searchedValue:
           pass
     

以问题为例(以列表形式)...

电子表格:[[11, 12, 13, 14 ...],[21, 22, 23, 24 ...], [31, 32, 33, 34 ...] ...]

数据框:[[A, B, C, D ...], [21, 22, 23, 24 ...], [31, 32, 33, 34 ...] ...]

代替[[A, B, C, D ...], [11, 12, 13, 14 ...] ...]

我在没有的情况下尝试了它,xl.parse(..., names = ...)然后添加了列,df_sheetExtraction.columns = sheetHeader 结果相同。不同的用法xl.parse(..., header = ...)不会影响目标结果。

有没有办法避免将数据框与单独的“标头数据框”结合起来?

谢谢你的帮助

标签: pythonexcelpandas

解决方案


header参数说(强调我的):

header : int, list of int, 默认 0 Row (0-indexed) 用于解析后的 DataFrame 的列标签。如果传递了一个整数列表,这些行位置将被组合成一个MultiIndex. 如果没有标题,请使用 None。

如果您希望将自己的列表添加为列名而不替换电子表格中的任何数据,您可以先设置header=None名称,然后再设置名称,例如

dfs = pd.read_excel(xlsx_filename,
                       sheet_name=[sheet_name_1,sheet_name_2],
                       header=None,
                       names=['Column_A','Column_B'])

推荐阅读