如何根据列值重命名Pandas列并将未知列移至DataFrame末尾
Pandas DataFrame列值错位修复方案
核心步骤拆解
- 识别需调整的列:先找出所有包含带
|单元格的列,这类列是值错位的重灾区,其余列保持原样。 - 按前缀映射值到正确列:拆分带
|单元格的前缀与内容,将内容移到对应前缀的列下。 - 迁移非空“未知”列到末尾:筛选出有值的“未知”类列,统一移到DataFrame最后。
代码实现
假设原始错位DataFrame为df,直接运行以下代码即可完成修复:
import pandas as pd import numpy as np # 1. 找出所有含|的列 cols_with_pipe = df.columns[df.apply(lambda x: x.astype(str).str.contains('\|').any(), axis=0)] # 2. 按前缀映射值到正确列 temp_df = df.copy() for idx, row in temp_df.iterrows(): for col in cols_with_pipe: cell_val = str(row[col]) if pd.notna(row[col]) and '|' in cell_val: # 拆分前缀和内容(只拆分第一个|) prefix, content = cell_val.split('|', 1) # 若前缀对应列存在,转移值并清空原单元格 if prefix in temp_df.columns: temp_df.loc[idx, prefix] = content temp_df.loc[idx, col] = np.nan # 3. 筛选有值的未知列并移到末尾 unknown_cols = [col for col in temp_df.columns if '未知' in col and temp_df[col].notna().any()] # 重新排列列顺序 final_cols = [col for col in temp_df.columns if col not in unknown_cols] + unknown_cols final_df = temp_df[final_cols]
关键细节说明
- 如果你的前缀分隔符不是
|,只需修改split('|', 1)中的分隔符即可。 - 若“未知”列的命名是“未知5”“未知6”这类带序号的形式,筛选逻辑
'未知' in col依然有效,无需额外调整。 - 无
|的列全程未被修改,列名和值都会保持原始状态,符合要求。
内容的提问来源于stack exchange,提问作者qbbq
相关产品推荐
相关产品推荐

