![](/img/trans.png)
[英]How do I append the data in text files and combine multiple text files into one text file using python?
[英]Python: How to Combine (concat) Multiple Excel Files into One File? (Not append)
每个部门在Excel中完成年度预算并提交预算。 单独的预算被汇总到一个单一的主预算中。
我过去曾使用过文件链接 Excel 公式,但这可能非常耗时且容易出现人为错误。
我认为这对于带有 Pandas(和/或其他库)的 Python 来说是一项完美的工作。
这是图片示例数据:
这是我迄今为止尝试过的:(从原始编辑/清理了一点)
#import libraries
import pandas as pd
import glob
# import excel files
path = '*.xlsx'
files = glob.glob(path)
# loop thru
combined_files = pd.DataFrame()
for i in files:
df = pd.read_excel(i, index_col=None, skiprows=11,
nrows=147, usecols='D:P')
combined_files = combined_files.concat(df)
combined_files.to_excel('output4.xlsx', index=False)
如果我运行 print(files) 文件被列出
我还尝试了“combined_excels”变量的变体,但没有任何乐趣。
期望的输出:
电子表格或 .csv,在第一列中具有总分类帐描述(即“供应品”),然后是所有文件的合并金额; 一月、二月、三月等
因此,如果部门 1 一月份的供应预算为 100 美元,部门 2 一月份的供应预算为 200 美元,部门 3 一月份的供应预算为 400 美元,那么结果将显示:供应:一月份以下将是:700 美元。
我将有大约 65 个不同的 Excel 文件,并且需要遍历列表。 大多数工作簿有多个工作表。 所有的工作表都有一个名为“预算”的表,这就是我们从中提取的。
我从我的三个示例文件中删除了所有支持表,因此我还不必处理这方面的问题,但我需要尽快添加该过滤器。
感谢您提供的任何帮助!
约翰
试试这个代码,你的循环直通和连接:
# Budget Roll-up
# Used to roll-up individual budgets into one master budget
#import libraries
import pandas as pd
import glob
# import excel files
path = '*.xlsx'
files = glob.glob(path)
# loop thru
combined_files = pd.DataFrame()
for i in files:
df = pd.read_excel(i, index_col=None,
skiprows=11, nrows=147, usecols='D:P')
df.rename(columns={ df.columns[0]: 'test'}, inplace = True)
df.set_index('test', inplace=True)
combined_files = combined_files.add(df, fill_value=0, axis=1)
combined_files.to_excel('output.xlsx', index=False)
在 Pandas 中阅读这些 excel 文件后,使用以下函数:
combined_excels = pd.concat((df1, df2), axis = 0)
如果你想垂直连接它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.