Python在excel工作表中循环,将sheetname添加到列表中,然后继续
我正在循环浏览Excel工作表并将其添加到列表中。当循环结束时,我使用Pandas连接到单个数据帧。我遇到的问题是将工作表名称添加到相应的列表中Python在excel工作表中循环,将sheetname添加到列表中,然后继续,python,excel,pandas,Python,Excel,Pandas,我正在循环浏览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_nam
# 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)
谢谢@jpp这正是我想要的!