Python、Pandas、组合来自x个excel文档的特定表格的数据
我正在尝试创建一系列函数,以便将x个excel文档的特定表格中的数据提取到一个数据框中 到目前为止,我得到的是:Python、Pandas、组合来自x个excel文档的特定表格的数据,excel,python-3.x,pandas,Excel,Python 3.x,Pandas,我正在尝试创建一系列函数,以便将x个excel文档的特定表格中的数据提取到一个数据框中 到目前为止,我得到的是: import os import glob os.chdir(r'path') FileList = glob.glob('*.xlsm') print(FileList) for file in FileList: df = extract_account(file, '2016') df = df.dropna() df_combined = pd.c
import os
import glob
os.chdir(r'path')
FileList = glob.glob('*.xlsm')
print(FileList)
for file in FileList:
df = extract_account(file, '2016')
df = df.dropna()
df_combined = pd.concat([df])
然而,当我调用
df_combined
时,它只返回一个df(我希望在测试中至少返回5个)extract\u account(文件名、工作表名)
是我创建的一个函数,它为一个文件提取我想要的数据,并返回pandas.core.frame.DataFrame
对象。然后,我的下一步是向这个函数传递一个要从中提取的年份列表 这里需要创建数据帧列表,然后一起创建,另外参数ignore_index=True
用于避免在final数据帧中重复索引值:
dfs = []
for file in FileList:
df = extract_account(file, '2016')
df = df.dropna()
dfs.append(df)
df_combined = pd.concat(dfs, ignore_index=True)
如果还希望按年份循环:
years = range(2016, 2020)
dfs = []
for file in FileList:
for year in years:
df = extract_account(file, str(year))
df = df.dropna()
dfs.append(df)
df_combined = pd.concat(dfs, ignore_index=True)
具有列表理解功能的解决方案:
dfs = [extract_account(file, '2016').dropna() for file in FileList]
df_combined = pd.concat(dfs, ignore_index=True)
谢谢你。但是,我想水平添加这些,而您的解决方案会垂直添加?@Maverick-因此需要df_combined=pd.concat(dfs,ignore_index=True,axis=1)
?是的,谢谢您的帮助。对不起,熊猫还不太熟练,还在学习@特立独行-不客气,顺便说一句,没有必要的借口:)
dfs = [extract_account(file, str(y)).dropna() for file in FileList for y in years]