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

如何高效使用np.where优化pandas多条件列赋值?

高效实现多条件DataFrame列填充(pandas + numpy)

针对你用重复条件填充新列的问题,这里提供几种更简洁高效的实现方式,尤其适合大规模数据集:

方案1:提取公共条件 + 年份映射

先把重复的price和fuel description条件提取出来,再用字典映射年份对应的值,最后一次性赋值:

# 定义公共过滤条件
common_condition = (df['price'] > 30000) & (df['fuel description'] == 'Petrol')

# 年份与目标值的映射字典
year_value_map = {
    2018: 12,
    2019: 15,
    2020: 18,
    2021: 21,
    2022: 24
}

# 赋值:满足公共条件时用映射值,否则用10;映射不到的年份也默认10
df['new_column'] = np.where(common_condition, df['year'].map(year_value_map).fillna(10), 10)

方案2:使用numpy.select处理多分支条件

如果需要更清晰的多条件分支逻辑,np.select是更好的选择,避免多次覆盖列值:

common_condition = (df['price'] > 30000) & (df['fuel description'] == 'Petrol')

# 列出所有需要匹配的子条件
conditions = [
    common_condition & (df['year'] == 2018),
    common_condition & (df['year'] == 2019),
    common_condition & (df['year'] == 2020),
    common_condition & (df['year'] == 2021),
    common_condition & (df['year'] == 2022)
]

# 对应每个条件的目标值
target_values = [12, 15, 18, 21, 24]

# 赋值:匹配到第一个条件用对应值,都不满足用默认10
df['new_column'] = np.select(conditions, target_values, default=10)

方案3:利用年份与值的线性关系(适用时)

观察到年份每增加1,目标值增加3,存在线性关系:值 = 3*(年份 - 2018) + 12,可以直接计算赋值,无需映射:

# 公共条件加上年份范围限制
common_condition = (df['price'] > 30000) & (df['fuel description'] == 'Petrol') & (df['year'].between(2018, 2022))

# 通过线性公式计算目标值
df['new_column'] = np.where(common_condition, 3 * df['year'] - 6042, 10)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 21:30:51