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

如何使用另一个DataFrame修改Pandas DataFrame的表头

用另一DataFrame的映射关系重命名DataFrame列

可以通过以下步骤实现需求:

  1. 将日期映射表转为字典:把DataFrame2的week列作为键,date列作为值,生成周数到日期的映射字典,快速匹配列名。
  2. 重命名目标DataFrame的列:利用pandas的rename()方法,结合上述字典替换DataFrame1中对应的列名,保留emp_id列不变。

完整代码示例

import pandas as pd

# 构造DataFrame1
df1 = pd.DataFrame({
    'emp_id': [101, 102, 103],
    'Week 41': [3, 2, 7],
    'Week 40': [5, 6, 5],
    'Week 39': [5, 4, 3],
    'Week 38': [7, 3, 6]
})

# 构造DataFrame2
df2 = pd.DataFrame({
    'week': ['Week 35', 'Week 36', 'Week 37', 'Week 38', 'Week 39', 'Week 40', 'Week 41'],
    'date': ['Aug-29 - Sep-03', 'Sep-05 - Sep-10', 'Sep-12 - Sep-17', 'Sep-19 - Sep-24', 'Sep-26 - Oct-01', 'Oct-03 - Oct-08', 'Oct-10 - Oct-15']
})

# 生成周数到日期的映射字典
week_to_date = df2.set_index('week')['date'].to_dict()

# 重命名df1的列:仅替换存在于字典中的列名,emp_id保持不变
df1_renamed = df1.rename(columns=week_to_date)

# 输出结果
print(df1_renamed.to_csv(index=False))

输出结果

emp_id,Oct-10 - Oct-15,Oct-03 - Oct-08,Sep-26 - Oct-01,Sep-19 - Sep-24
101,3,5,5,7
102,2,6,4,3
103,7,5,3,6

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:45:32