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

如何用Pandas将DataFrame中col1的0值替换为同行col2的值?

替换DataFrame中指定列的0值为同行另一列的值

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

  • 使用mask()方法:

    df['col1'] = df['col1'].mask(df['col1'] == 0, df['col2'])
    

    mask()会在第一个参数的条件为真时,将对应位置的值替换为第二个参数的内容,刚好匹配需求。

  • 使用loc索引直接赋值:

    df.loc[df['col1'] == 0, 'col1'] = df.loc[df['col1'] == 0, 'col2']
    

    直接定位到col1值为0的行,将这些行的col1值替换为同行col2的值,逻辑直观清晰。

  • 使用where()方法:

    df['col1'] = df['col1'].where(df['col1'] != 0, df['col2'])
    

    where()与mask()逻辑相反,当条件为真时保留原数值,条件为假时替换为指定值,这里就是当col1不等于0时保留原值,等于0时用col2的值替代。

这几种方法都能高效实现需求,其中mask()和where()的代码更简洁,loc方式更适合新手理解逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 08:48:15