我正在循环遍历Excel工作表并将它们添加到列表中。当循环结束时,我使用Pandas将它们合并成一个数据框(dataframe)。我的问题是如何将工作表名称添加到相应的列表中。
# 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中创建一个新列,但是这导致了长度不匹配,并且由于它不断地被重写到循环中的最后一个工作表名称,所以也没有起作用。您有什么想法或建议吗?