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

如何在DataFrame中根据另一列更新列值(空值时保留原值)

问题描述

我有如下DataFrame:

Id    date          sales  sales_new
291   2022-03-01     10       15 
292   2022-04-01     12       16
293   2022-05-01      9        0 
294   2022-06-01     13       20
295   2022-07-01     10       nan
296   2022-08-01     12       nan

需求是:当sales_new列存在有效值(包括0)时,用其替换sales列的值;当sales_new列为nan时,保留sales列的原值。期望得到的结果如下:

Id    date          sales  
291   2022-03-01     15       
292   2022-04-01     16      
293   2022-05-01      0       
294   2022-06-01     20      
295   2022-07-01     10       
296   2022-08-01     12
解决方案

以下是几种简洁的实现方式:

方法1:使用combine_first

该方法会优先取调用者(sales_new)的有效值,当调用者值为NaN时,用传入的sales值填充,正好匹配需求:

df['sales'] = df['sales_new'].combine_first(df['sales'])
# 按需删除sales_new列
df = df.drop('sales_new', axis=1)

方法2:使用fillna

直接用sales填充sales_new中的NaN值,再赋值回sales列:

df['sales'] = df['sales_new'].fillna(df['sales'])
df = df.drop('sales_new', axis=1)

方法3:使用numpy.where

通过条件判断显式控制赋值逻辑,可读性强:

import numpy as np
df['sales'] = np.where(df['sales_new'].notna(), df['sales_new'], df['sales'])
df = df.drop('sales_new', axis=1)

以上三种方法都能正确处理sales_new为0的情况(0属于有效值,不会被判定为NaN),最终得到目标结果。

内容的提问来源于stack exchange,提问作者Julio Moyano Basso

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 11:20:30