You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于指定映射字典重命名df2列名并筛选目标列

解决方法

首先修正你代码里的语法错误:df1_cols_to_rename_df2的结尾多了个方括号,正确的字典定义如下:

df1_cols_to_rename_df2 = {'first_column':['1st_column'], 'second_column':['2nd_column'], 'third column':['3rd_column'],'fourth_column':['4th_column']}

接下来按需求处理df2,分两步完成:筛选保留列、重命名列名:

  1. 构建反向映射字典
    原字典是{目标列名: [原df2列名]}的结构,而pandas的rename方法需要{原列名: 目标列名}的映射,所以先反转字典:
rename_map = {}
for new_col, old_cols in df1_cols_to_rename_df2.items():
    for old_col in old_cols:
        rename_map[old_col] = new_col
  1. 筛选并重命名列
    先从df2中提取所有在映射范围内的列,再用上面的映射表重命名列名:
# 筛选需要保留的列,并重命名
processed_df2 = df2[rename_map.keys()].rename(columns=rename_map)
  1. 输出处理后的结果
    打印最终的DataFrame:
print(processed_df2)

运行后得到的结果与预期一致,仅包含映射后的四列:

first_column second_column third column fourth_column
0            1             1            1             7
1            2             5            2             2
2            4             3            2             2

内容的提问来源于stack exchange,提问作者yoopiyo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 13:56:40