【问题标题】:What would be an elegant solution to managing and getting data from multiple excel files从多个 Excel 文件中管理和获取数据的优雅解决方案是什么?
【发布时间】:2016-09-09 20:24:57
【问题描述】:
好的,所以我发现我需要遵守来自多个报告的数据(大约 700 个/月)。它们都在一张 xls 文件中,并且它们的结构是相同的(标准标题和列,除了行数)。
我目前正在使用 VBA 粘贴公式行并将值复制到主表中,但有时我发现这是一个烦躁的过程。
我计划在地图上(请注意文件不包含位置信息)或图表中显示数据。
处理这个问题的优雅方法是什么?
【问题讨论】:
标签:
database
excel
pandas
maps
visualization
【解决方案1】:
import pandas as pd # pandas library
import re # regular expression library for advanced text matching
from os.path import basename # basename: to strip filename from path
# This can be whatever path you need. eg 'C:/myfiles/'
# './' is a reference to the current path and assumes all your files
# are located in the same directory you are running your script.
path = './'
# Get all '.xlsx' files in path
# this is just a way to get a list of file names into a list.
# if you have another way to get this done... fantastic.
filenames = [fn for fn in os.listdir(path) if re.match(r'\.xlsx$', fn)]
# one of my favorite pandas funcitons. It will push together a bunch of
# dataframes together either vertically, or horizontally if axis=1 is passed
# In this case, I chose horizontally. So you'd expect a large dataframe
# with top level column indices specifying the name of the file it came from.
df = pd.concat(
[pd.read_excel(fn) for fn in filenames],
axis=1,
keys=[basename(fn).strip('.xlsx') for fn in filenames]
)
请记住,您提出了一个相当模糊的问题。我提供的是关于如何去做的指导。您的里程可能会有所不同,您可能需要对特定元素进行更多研究。甚至可以提出更多问题。
【解决方案2】:
import pandas as pd
from glob import glob
files = glob('path/to/files/*.xlsx')
df = pd.concat([pd.read_excel(f) for f in files])
df.to_excel('master.xlsx', index=False)
glob 返回所有 xlsx 文件的列表
然后我们使用pd.read_excel 从该列表中的每个文件创建一个DataFrame,并将它们传递给pd.concat,它返回一个DataFrame。
df = pd.concat([pd.read_excel(f) for f in files])
最后,您可以保存到主文件
df.to_excel('master.xlsx', index=False)