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

如何基于source列的条件向Pandas DataFrame添加year_23列?

给Pandas DataFrame新增依赖source列的静态值列

方法1:字典映射(最直观)

先定义source取值与对应Fy_23静态值的映射字典,再通过map()方法快速生成新列:

import pandas as pd

# 示例DataFrame(替换成你的实际数据)
df = pd.DataFrame({'source': ['X', 'Y', 'X', 'Z', 'Y']})

# 定义映射规则:key是source的取值,value是对应的year_23值
source_map = {
    'X': 3000,
    'Y': 4500,
    'Z': 3800
}

# 新增year_23列
df['year_23'] = df['source'].map(source_map)

如果source中存在不在映射字典里的取值,map()会返回NaN,可以用fillna()设置默认值:

df['year_23'] = df['source'].map(source_map).fillna(0)  # 0为默认值,可根据需求修改

方法2:使用replace()方法

replace()可以直接将source的取值替换为对应静态值,适合需要保留未匹配原取值的场景:

df['year_23'] = df['source'].replace(source_map)

注:未在映射字典中的source取值,会保留原内容而非转为NaN。

方法3:numpy.where(适合少量条件)

如果source的取值类别较少,可通过嵌套np.where逐个判断赋值:

import numpy as np

df['year_23'] = np.where(df['source'] == 'X', 3000,
                        np.where(df['source'] == 'Y', 4500,
                                np.where(df['source'] == 'Z', 3800, 0)))

这种方式在条件较多时会导致代码冗余,优先推荐前两种方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:50:28