文件夹中有以2-开头的xlsx文件,合并这些文件,每个表中有很多的续表,根据正则表达式判断续表,同时以城市为键,合并这些表格包括续表
时间: 2024-01-13 07:02:33 浏览: 69
好的,您可以使用Python中的pandas库来完成这个任务。首先,您需要使用正则表达式来筛选以2-开头的xlsx文件,并将这些文件读取到pandas的DataFrame中。然后,您可以使用正则表达式来判断哪些行是续表,并将它们添加到之前的表格中。最后,根据城市为键将所有表格合并。
以下是示例代码:
```python
import os
import re
import pandas as pd
# 正则表达式
regex = re.compile(r'^2-.*\.xlsx$')
continuation_regex = re.compile(r'^\d+\s.*$') # 这里假设续表的第一列为数字加空格
# 读取所有符合条件的xlsx文件
files = [f for f in os.listdir('.') if os.path.isfile(f) and regex.match(f)]
dfs = []
for file in files:
df = pd.read_excel(file, sheet_name=None, engine='openpyxl')
for sheet_name, sheet_df in df.items():
# 判断续表并添加到之前的表格中
if sheet_df.iloc[0, 0] and continuation_regex.match(str(sheet_df.iloc[0, 0])):
dfs[-1] = pd.concat([dfs[-1], sheet_df])
else:
dfs.append(sheet_df)
# 合并所有表格
merged_df = pd.concat(dfs)
# 根据城市为键合并所有表格
grouped_df = merged_df.groupby('城市').agg(lambda x: x.tolist())
# 将所有列表转换为字符串并重新转换为DataFrame
grouped_df = grouped_df.applymap(lambda x: ','.join([str(i) for i in x]))
grouped_df = pd.DataFrame(grouped_df.to_dict())
# 输出结果
print(grouped_df)
```
请注意,这只是示例代码,您需要根据实际情况进行调整。
阅读全文
相关推荐














