|
发表于 2024-6-28 22:16:52
|
显示全部楼层
嘿嘿,鱼儿,这可不是鱼鳞掉到你的盘子里了,而是因为在使用`pandas.DataFrame.to_excel`时,DataFrame的索引会默认作为第一列导出。如果你不需要索引导出,只需设置`index=False`就可以啦。
首先,让我们调整一下函数`extract_tables_from_excel`。然后修改`main`函数,以确保在导出Excel时没有多余的索引。
以下是修正后的代码:
- import pandas as pd
- import os
- # 拆分表格函数
- def extract_tables_from_excel(file_path, sheet_name='Sheet1'):
- df = pd.read_excel(file_path, sheet_name=sheet_name)
- tables = []
- temp_df = []
- # 分割逻辑:遇到空行就分割
- for _, row in df.iterrows():
- if row.isnull().all(): # 判断空行
- if temp_df:
- tables.append(pd.DataFrame(temp_df))
- temp_df = []
- else:
- temp_df.append(row)
- if temp_df:
- tables.append(pd.DataFrame(temp_df))
- return tables
- # 合并表格函数
- def merge_tables(merging_tables, existing_tables):
- merged_tables = []
- for new_table, old_table in zip(merging_tables, existing_tables):
- if not old_table.empty:
- merged_table = pd.concat([old_table, new_table], ignore_index=True)
- else:
- merged_table = new_table
- merged_tables.append(merged_table)
- return merged_tables
- # 主函数
- def main(input_files, existing_files, output_dir):
- all_existing_tables = [pd.read_excel(file) for file in existing_files]
- for file in input_files:
- merging_tables = extract_tables_from_excel(file)
- all_existing_tables = merge_tables(merging_tables, all_existing_tables)
- # 输出合并后的表格
- for idx, table in enumerate(all_existing_tables):
- output_file_path = os.path.join(output_dir, f'merged_output_{idx + 1}.xlsx')
- table.to_excel(output_file_path, index=False) # 确保 index=False
- print(f'Saved merged table to {output_file_path}')
- # 示例的输入文件路径列表
- input_files = [r'路径1.xlsx', r'路径2.xlsx']
- existing_files = [r'已有路径1.xlsx', r'已有路径2.xlsx']
- output_dir = r'D:\2024年6月14日周督促会\统计'
- main(input_files, existing_files, output_dir)
复制代码
### 解释:
1. **提取表格**:`extract_tables_from_excel` 函数把每个表格从Excel文件中拆分出来,遇到空行就分割。
2. **合并表格**:`merge_tables` 函数将新表格和现有表格进行合并。
3. **主函数**:`main` 函数读取所有输入文件,并调用拆分和合并函数处理数据,然后将结果保存到指定目录下的新Excel文件中。
4. **防止索引输出**:`table.to_excel(output_file_path, index=False)` 这行代码确保了导出Excel时不会带上多余的索引。
这样,你的表格应该干净整洁,没有多余的“Unnamed”列。快试试吧,再次祝你“小鱼干”大丰收!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|