Python循环遍历Excel工作表,将工作表名称添加到列表中,然后连接所有

2024-06-20

我正在循环遍历 Excel 工作表并将它们附加到列表中。循环完成后,我使用 Pandas 连接到单个数据帧。我遇到的问题是将工作表名称添加到适当的列表中。

# infile is a filepath variable    
xls = xlrd.open_workbook(infile, on_demand=True)



dfList = []
for sheet_name in xls.sheet_names():
    df = pd.read_excel(infile, sheet_name, header = 0)
    #df['Well_name'] = sheet_name
    dfList.append(df)
    print(sheet_name + " appended.")
    #time.sleep(2)
print("Loop complete")
# Concatenating the appended lists
dfs = pd.concat(dfList, axis=0)

我尝试在 df 中创建一个新列,但这导致长度不匹配,而且它也不起作用,因为它不断被重写为循环中的最后一个工作表名称。

有什么想法或建议吗?


您似乎遇到了一些范围界定问题。避免此问题的一种方法是使用列表理解。您还可以使用pd.DataFrame.assign在列表理解中添加一系列:

dfList = [pd.read_excel(infile, sheet_name, header=0).assign(Well_name=sheet_name) \
          for sheet_name in xls.sheet_names()]

dfs = pd.concat(dfList, axis=0)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python循环遍历Excel工作表,将工作表名称添加到列表中,然后连接所有 的相关文章

随机推荐