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

Python中为DataFrame新增列:匹配现有列键填充字典对应值

问题需求

刚接触Python及pandas/numpy,需要为现有DataFrame新增一列:当DataFrame中Name列的值与给定字典的键匹配时,填充字典对应的value;不匹配则填充空字符串。

初始数据

DataFrame

NameFonderYear
0company1person11999
1company2person22000
2company3person32001
3company4person42002
4company5person52003

匹配字典

col_dict = {'company2': 'abc', 'company4': 'xyz',}

解决方案

使用pandas的map()方法结合fillna()即可实现需求:

import pandas as pd

# 假设你的DataFrame变量名为df
df['new_col'] = df['Name'].map(col_dict).fillna('')
  • df['Name'].map(col_dict):将Name列的每个值与字典col_dict的键匹配,返回对应value,不匹配的返回NaN
  • .fillna(''):将所有NaN替换为空字符串

预期结果

NameFonderYearnew_col
0company1person11999
1company2person22000abc
2company3person32001
3company4person42002xyz
4company5person52003

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 02:35:20