python - 如何在不覆盖 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 = ...)
不会影响目标结果。
有没有办法避免将数据框与单独的“标头数据框”结合起来?
谢谢你的帮助
解决方案
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'])
推荐阅读
- java - 这将是一个 if 语句
- json - 有没有办法将分支合并状态信息转换为 JSON?
- pdf - 如何使用ghostscript检查pdf是否已经转换为pdf/a?
- sql-server - 安装了 SQLENGINE 的 SQL2019 显示 4 个新系统文件,但 SSMS 中没有新系统数据库
- javascript - 类型错误:这是未定义的“反应”
- c++ - 初始化具有显式大小的数组是否需要 constexpr 大小?
- android - 新的 pubspec Flutter 插件声明导致 MissingPluginException
- javascript - Nuxt mixin - 属性或方法未在实例上定义,但在渲染期间引用
- javascript - 如何在单击事件期间禁用自动滚动到顶部
- perl - 我如何翻转 ord('a') 的位