ℕʘʘ*_*ḆḽḘ 3 python excel dataframe pandas
我有一个很大的Excel文件,其中包含许多不同的工作表。所有工作表都具有相同的结构,例如:
Name
col1 col2 col3 col4
1 1 2 4
4 3 2 1
Run Code Online (Sandbox Code Playgroud)
Pandas而不必手动命名每个工作表?如果这些是文件,则可以glob用来获取目录中的文件列表。但是在这里,对于excel表格,我迷路了。谢谢!
尝试这个:
dfs = pd.read_excel(filename, sheetname=None, skiprows=1)
Run Code Online (Sandbox Code Playgroud)
这将为您返回DF的字典,您可以使用pd.concat(dfs)或如同@jezrael在其答案中已经张贴的那样轻松地将其连接:
df = pd.concat(pd.read_excel(filename, sheetname=None, skiprows=1))
Run Code Online (Sandbox Code Playgroud)
sheetname:无->将所有工作表作为DataFrames的字典
更新:
有没有一种方法可以在结果数据框中创建一个变量,以标识数据来源的图纸名称?
dfs = pd.read_excel(filename, sheetname=None, skiprows=1)
Run Code Online (Sandbox Code Playgroud)
假设我们有以下命令:
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}
Run Code Online (Sandbox Code Playgroud)
现在我们可以添加一个新列:
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
Run Code Online (Sandbox Code Playgroud)
从这个问题中记下:
import pandas as pd
file = pd.ExcelFile('file.xlsx')
names = file.sheet_names # see all sheet names
df = pd.concat([file.parse(name) for name in names])
Run Code Online (Sandbox Code Playgroud)
结果:
df
Out[6]:
A B
0 1 3
1 2 4
0 5 6
1 7 8
Run Code Online (Sandbox Code Playgroud)
然后你可以运行df.reset_index(), 重置索引。
编辑:pandas.ExcelFile.parse根据 pandas 文档:
相当于 read_excel(ExcelFile, ...) 有关接受参数的更多信息,请参阅 read_excel 文档字符串