如何用Pandas拆分多列表格并合并为单表且添加道路名列
解决方案
步骤说明
- 定位分隔多组表格的全NaN列,以此拆分出独立子表格
- 为每个子表格设置正确表头,过滤掉表头行
- 为每组表格添加对应道路名列
- 合并所有子表格为单个DataFrame
完整代码
import pandas as pd import numpy as np # 测试数据转换为DataFrame test_data = {'Unnamed: 0': {0: 'Start Time', 1: '06:01:00', 2: '06:31:00', 3: '07:31:00', 4: '08:31:00'}, 'Unnamed: 1': {0: 'End Time', 1: '06:30:00', 2: '07:30:00', 3: '08:30:00', 4: '09:30:00'}, 'Unnamed: 2': {0: 'Number of Cars', 1: '5343', 2: '2545', 3: '2434', 4: '3424'}, 'Unnamed: 3': {0: np.nan, 1: np.nan, 2: np.nan, 3: np.nan, 4: np.nan}, 'Unnamed: 4': {0: 'Start Time', 1: '06:01:00', 2: '06:31:00', 3: '07:31:00', 4: '08:31:00'}, 'Unnamed: 5': {0: 'End Time', 1: '06:30:00', 2: '07:30:00', 3: '08:30:00', 4: '09:30:00'}, 'Unnamed: 6': {0: 'Number of Cars', 1: '5343', 2: '2545', 3: '2434', 4: '3424'}, 'Unnamed: 7': {0: np.nan, 1: np.nan, 2: np.nan, 3: np.nan, 4: np.nan}, 'Unnamed: 8': {0: 'Start Time', 1: '06:01:00', 2: '06:31:00', 3: '07:31:00', 4: '08:31:00'}, 'Unnamed: 9': {0: 'End Time', 1: '06:30:00', 2: '07:30:00', 3: '08:30:00', 4: '09:30:00'}, 'Unnamed: 10': {0: 'Number of Cars', 1: '5343', 2: '2545', 3: '2434', 4: '3424'}} df = pd.DataFrame(test_data) # 1. 识别分隔列:全为NaN的列 separator_cols = df.columns[df.isna().all()].tolist() # 2. 划分表格列组:将连续的非分隔列分为一组 col_groups = [] current_group = [] for col in df.columns: if col in separator_cols: if current_group: col_groups.append(current_group) current_group = [] else: current_group.append(col) # 添加最后一组 if current_group: col_groups.append(current_group) # 3. 处理每个表格组 result_dfs = [] for idx, cols in enumerate(col_groups, 1): # 提取子表格 sub_df = df[cols].copy() # 设置表头为第一行 sub_df.columns = sub_df.iloc[0].tolist() # 跳过表头行,保留数据行 sub_df = sub_df[1:].reset_index(drop=True) # 添加道路名列 sub_df['道路名'] = f'道路{idx}' result_dfs.append(sub_df) # 4. 合并所有子表格 final_df = pd.concat(result_dfs, ignore_index=True) print(final_df)
代码解释
- 识别分隔列:通过
df.isna().all()判断每列是否全为NaN,这类列就是不同表格的分隔符 - 划分列组:遍历所有列,将连续的非分隔列归为一组,每组对应一个独立表格
- 处理子表格:
- 提取子DataFrame后,将第一行设为表头
- 移除表头行,仅保留实际数据行
- 添加道路名列,示例中用序号命名(若Excel中存在原始道路名,可替换为对应读取逻辑)
- 合并结果:使用
pd.concat将所有子表格合并为一个完整的DataFrame
内容的提问来源于stack exchange,提问作者z star
相关产品推荐
相关产品推荐

