我有一个很大的 Excel 文件,其中包含许多不同的工作表。所有工作表都具有相同的结构,例如:
Name
col1 col2 col3 col4
1 1 2 4
4 3 2 1
- 如何在
Pandas
中(垂直)连接所有这些工作表,而不必手动为每个工作表命名?如果这些是文件,我可以使用glob
获取目录中的文件列表。但在这里,对于 Excel 工作表,我迷路了。 - 有没有办法在生成的数据框中创建一个变量来标识数据来自的工作表名称?
谢谢!
最佳答案
试试这个:
dfs = pd.read_excel(filename, sheet_name=None, skiprows=1)
这将返回一个 DF 字典,您可以使用 pd.concat(dfs)
轻松连接它,或者 @jezrael 已经在他的回答中发布:
df = pd.concat(pd.read_excel(filename, sheet_name=None, skiprows=1))
sheet_name:无 -> 所有工作表作为 DataFrames 的字典
更新:
Is there a way to create a variable in the resulting dataframe that identifies the sheet name from which the data comes from?
dfs = pd.read_excel(filename, sheet_name=None, skiprows=1)
假设我们有以下命令:
In [76]: dfs
Out[76]:
{'d1': col1 col2 col3 col4
0 1 1 2 4
1 4 3 2 1, 'd2': col1 col2 col3 col4
0 3 3 4 6
1 6 5 4 3}
现在我们可以添加一个新列:
In [77]: pd.concat([df.assign(name=n) for n,df in dfs.items()])
Out[77]:
col1 col2 col3 col4 name
0 1 1 2 4 d1
1 4 3 2 1 d1
0 3 3 4 6 d2
1 6 5 4 3 d2
关于python - 如何连接来自同一文件的多个Excel工作表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46605910/