使用for循环导入3个Excel文件合并为Pandas DataFrame的问题及解决
导入多个Excel文件合并为Pandas DataFrame的循环写法问题排查
需要导入3个.xlsx格式文件并合并为1个Pandas DataFrame,目标是使用for循环避免重复编写代码,以下是不同版本代码的问题和修正方案:
原始重复代码
filepath_1 = input('Enter Revenue Month M1 File Path: ') revenue_month_1 = pd.read_excel(filepath_1) revenue_month_1 = revenue_month_1.apply(pd.to_numeric, errors='ignore') revenue_month_1['Month'] = pd.to_datetime(revenue_month_1['Month'], format='%Y%m', errors='coerce').dropna() filepath_2 = input('Enter Revenue Month M2 File Path: ') revenue_month_2 = pd.read_excel(filepath_2) revenue_month_2 = revenue_month_2.apply(pd.to_numeric, errors='ignore') revenue_month_2['Month'] = pd.to_datetime(revenue_month_2['Month'], format='%Y%m', errors='coerce').dropna() filepath_3 = input('Enter Revenue Month M3 File Path: ') revenue_month_3 = pd.read_excel(filepath_3) revenue_month_3 = revenue_month_3.apply(pd.to_numeric, errors='ignore') revenue_month_3['Month'] = pd.to_datetime(revenue_month_3['Month'], format='%Y%m', errors='coerce').dropna()
初次改写的for循环代码及问题
问题代码
revenue_reports = [ input('Enter Revenue Month M1 File Path: '), input('Enter Revenue Month M2 File Path: '), input('Enter Revenue Month M3 File Path: '), ] revenue = [] for revenue_report in revenue_reports: revenue = pd.read_excel(revenue_report) revenue = revenue.apply(pd.to_numeric, errors='ignore') revenue['Month'] = pd.to_datetime(revenue['Month'], format='%Y%m', errors='coerce').dropna() revenue = revenue.append(revenue)
运行现象
执行后只能获取到3个月数据中最后一个月(M3)的内容。
错误原因
- 变量命名冲突:初始定义
revenue为存储所有单月数据的列表,但循环第一行就将revenue重新赋值为读取的单月DataFrame,直接覆盖了原列表,之前存储的内容全部丢失 - 追加逻辑错误:
revenue = revenue.append(revenue)是把当前单月数据追加到自身,只会让当前月数据重复一次,没有存入全局结果容器,循环结束后revenue自然只剩最后一次循环的M3数据
修正后代码
revenue_reports = [ input('Enter Revenue Month M1 File Path: '), input('Enter Revenue Month M2 File Path: '), input('Enter Revenue Month M3 File Path: '), ] revenue = [] x = 1 for revenue_report in revenue_reports: revenue_monthly = pd.read_excel(revenue_report) revenue_monthly = revenue_monthly.apply(pd.to_numeric, errors='ignore') revenue_monthly["M"+str(x)] = pd.to_datetime(revenue_monthly['Month'], format='%Y%m', errors='coerce').dropna() x += 1 revenue.append(revenue_monthly) revenue = pd.concat(revenue)
修正点说明
- 新增独立的单月数据变量
revenue_monthly,避免和结果列表重名 - 每次处理完的单月数据通过
append存入结果列表,最后用pd.concat合并所有数据 - 新增了
M1/M2/M3标识列,若不需要该标识,可直接保留原Month列即可
内容的提问来源于stack exchange,提问作者minnnmin
相关产品推荐
相关产品推荐

