繁体   English   中英

什么是从多个Excel文件管理和获取数据的绝佳解决方案

[英]What would be an elegant solution to managing and getting data from multiple excel files

好的,所以我发现我需要检查来自多个报告的数据(大约700个/月)。 它们全都放在一张工作表的xls文件中,并且它们的结构是相同的(标准标题和列,行数除外)。 我目前使用的VBA粘贴公式行并将其值复制到主表中,但是有时我会觉得这是一个烦躁的过程。 我正计划在地图(请注意文件中不包含位置信息)或图表中可视化数据。

用什么优雅的方式来解决这个问题?

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]
)

请记住,您问了一个相当模糊的问题。 我提供的是如何进行指导。 您的里程可能会有所不同,您可能需要对特定元素进行更多研究。 甚至可以问更多问题。

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM