python - 循环/迭代excel文件目录并添加到数据框的底部
问题描述
我目前正在使用 Python 导入和格式化大量的 excel 文件(格式/方案相同,但值不同)。
我已经读入并格式化了一个文件,到目前为止一切正常。我现在将对所有其他文件执行相同的操作,并将所有内容合并到一个数据框中,即在一个数据框中读取第一个 excel,在数据框底部添加第二个,在数据框底部添加第三个,依此类推直到我在一个数据框中拥有所有 excel 文件。
到目前为止,我的脚本看起来像这样:
import pandas as pd
import numpy as np
import xlrd
import os
path = os.getcwd()
path = "path of the directory"
wbname = "name of the excel file"
files = os.listdir(path)
files
wb = xlrd.open_workbook(path + wbname)
# I only need the second sheet
df = pd.read_excel(path + wbname, sheet_name="sheet2", skiprows = 2, header = None,
skipfooter=132)
# here is where all the formatting is happening ...
df
因此,“文件”是一个包含所有文件相关名称的列表。现在我必须尝试将一个文件一个接一个地放入一个循环中(?),以便它们最终都以 df 结尾。
有没有人做过这样的事情或者可以在这里帮助我。
解决方案
像这样的东西可能会起作用:
import os
import pandas as pd
list_dfs=[]
for file in os.listdir('path_to_all_xlsx'):
df = pd.read_excel(file, <the rest of your config to parse>)
list_dfs.append(df)
all_dfs = pd.concat(list_dfs)
您读取所有数据帧并将它们添加到列表中,然后 concat 方法将它们全部添加到一个大数据帧中。
推荐阅读
- c# - 数据网格中添加的默认原始数据
- angular - 添加了 Angular 收藏按钮,但颜色没有改变
- java - 将字符串保存为易于访问的文件格式(例如 XML)
- batch-file - 如何批量比较下载的内容
- python - 使用python从杂乱无章的xml文件中提取数据
- javascript - 为什么 Firefox 执行 XMLHttpRequest 与 Chrome/IE 不同?
- docker - 在您的集群中找不到活动节点 Laravel Docker elasticsearch
- css - 如何安排按钮来填充利润?
- python - Postgresql, Python - 编辑日期/时间将其导出并将其插入 SQL
- java - 在“java 代码”中的 weka 3.8 中缺少 LibSVM 包装器(我已经安装了它并且可以在实验者中看到它)