遍历文件夹,读取excel文件,并对数据进行concat拼接 python
时间: 2024-12-30 11:36:47 浏览: 136
在Python中,我们可以使用pandas库以及os和glob模块来遍历文件夹,查找Excel文件,然后读取它们并将数据进行拼接。以下是一个基本示例:
```python
import os
import glob
import pandas as pd
# 定义文件夹路径和Excel文件名模式
folder_path = "your_folder_path"
file_pattern = "*.xlsx" # 改成你需要匹配的Excel文件扩展名
# 使用glob找出文件夹中所有Excel文件
files = glob.glob(os.path.join(folder_path, file_pattern))
# 创建一个空的DataFrame来存放所有的数据
all_data = pd.DataFrame()
# 遍历每个文件
for file in files:
# 读取每个Excel文件
df_each = pd.read_excel(file)
# 将当前文件的数据追加到all_data DataFrame上
all_data = pd.concat([all_data, df_each])
# 如果你想保留唯一索引,可以在拼接后使用drop_duplicates()
all_data = all_data.drop_duplicates() if len(all_data.index.duplicated()) > 0 else all_data
# 输出结果
print(all_data)
#
相关问题
遍历文件夹,根据文件夹修改日期先后顺序读取excel文件,并对数据进行concat拼接 python
在Python中,你可以使用`os`模块来遍历文件夹,`datetime`模块处理修改日期,`pandas`库用于读取Excel文件并操作数据。这里是一个简单的示例,如何按照文件修改时间排序并concat拼接Excel文件:
```python
import os
import pandas as pd
from datetime import datetime
# 定义函数,遍历指定目录下的Excel文件
def read_excel_files(directory):
excel_files = [f for f in os.listdir(directory) if f.endswith('.xlsx') or f.endswith('.xls')]
# 按照文件修改时间排序
sorted_files = sorted(excel_files, key=lambda x: datetime.fromtimestamp(os.path.getmtime(os.path.join(directory, x))))
dfs = []
for file in sorted_files:
df = pd.read_excel(os.path.join(directory, file))
dfs.append(df)
# 使用pandas concat拼接所有数据
concatenated_df = pd.concat(dfs)
return concatenated_df
# 调用函数,传入你想遍历的文件夹路径
directory_path = 'your_directory_path'
result_df = read_excel_files(directory_path)
```
在这个例子中,`read_excel_files`函数首先列出指定目录下所有的Excel文件,然后按文件的最后修改时间(mtime)排序。接着,它读取每个文件,将其转换为DataFrame,然后合并所有DataFrame到一个大的DataFrame中。
python 使用pandas库,使用 pandas 库中的 read_excel 函数和 MultiIndex 类型来读取合并单元格表头,操作excel文件“data\推送名单.xlsx”,遍历循环读取所有sheet表,在最右侧添加一列,表头为“合并内容”,读取合并单元格表头“推送内容”的所在的合并列的所有数据data(示列:B列,C列,D列的第一行为合并单元格,数值是表头“推送内容”),定义一个字符串,对data数据进行遍历循环,每一行对列数据做字符串拼接strtext(表头为“推送内容”的合并列的单元格数据有转行,有特殊符号),生成的strtext写入到excel中的对应行的“合并表头”列,保存excel文件
好的,我来解答您的问题。
您可以按照以下步骤来实现您的需求:
1. 导入 pandas 库和 openpyxl 库(openpyxl 库是 pandas 库处理合并单元格表头需要用到的库):
```python
import pandas as pd
from openpyxl import load_workbook
```
2. 使用 read_excel 函数读取 Excel 文件,并通过 MultiIndex 类型处理合并单元格表头:
```python
# 读取 Excel 文件
file_path = 'data/推送名单.xlsx'
excel_file = pd.ExcelFile(file_path)
# 定义一个空的 DataFrame 保存所有 sheet 表的数据
data_all = pd.DataFrame()
# 遍历循环读取所有 sheet 表
for sheet_name in excel_file.sheet_names:
# 读取 sheet 表数据,并使用 MultiIndex 类型处理合并单元格表头
data = pd.read_excel(file_path, sheet_name=sheet_name, header=[0, 1], engine='openpyxl')
data_all = pd.concat([data_all, data], axis=0)
```
3. 定义一个函数,用于获取合并单元格表头“推送内容”的所在的合并列的所有数据:
```python
def get_merge_cells(sheet):
merge_cells = sheet.merged_cells
for merged_cell in merge_cells:
if merged_cell.start_row == 0 and merged_cell.start_column == 1:
merge_range = sheet[merged_cell.coord]
merge_values = [cell.value for row in merge_range for cell in row]
return merge_values
return []
```
4. 遍历循环 DataFrame 中的每一行,对列数据做字符串拼接,生成的 strtext 写入到 excel 中的对应行的“合并表头”列:
```python
# 打开 Excel 文件
excel_writer = pd.ExcelWriter(file_path, engine='openpyxl')
book = load_workbook(file_path)
excel_writer.book = book
# 遍历循环 DataFrame 中的每一行
for i, row in data_all.iterrows():
# 获取“推送内容”的合并列数据
sheet_name = row.name[0]
sheet = book[sheet_name]
merge_values = get_merge_cells(sheet)
# 对列数据做字符串拼接
strtext = ''
for col in ['B', 'C', 'D']:
if not pd.isna(row[(col, '推送内容')]):
strtext += str(row[(col, '推送内容')])
if str(row[(col, '推送内容')]).endswith('\n'):
strtext += '\n'
# 将生成的 strtext 写入到 excel 中的对应行的“合并表头”列
data_all.at[i, ('', '合并内容')] = strtext.strip()
# 将 DataFrame 保存到 Excel 文件中
data_all.to_excel(excel_writer, sheet_name='合并表头', index=False)
# 关闭 Excel 文件
excel_writer.save()
```
这样,您就可以使用 pandas 库和 openpyxl 库读取合并单元格表头,操作 excel 文件,并在最右侧添加一列,表头为“合并内容”,读取合并单元格表头“推送内容”的所在的合并列的所有数据,对数据进行遍历循环,每一行对列数据做字符串拼接,生成的 strtext 写入到 excel 中的对应行的“合并表头”列,最后保存 excel 文件。
阅读全文
相关推荐
















