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

如何在Pandas中根据符号替换列值并合并为单列?

Pandas高效合并两列(取每行正值)的方案

基于你给出的条件(每行中一列正、一列负),以下几种vectorized操作的方案都是高效的(避免逐行循环,利用Pandas/Numpy的内置优化):

  • 方法一:直接取每行最大值
    因为正数必然大于负数,直接对两列取行最大值即可得到目标结果:

    import pandas as pd
    
    # 构造示例DataFrame
    df = pd.DataFrame({
        'col1': [0.4, 0.2, -0.1, -0.2, 0.8],
        'col2': [-0.9, -0.5, 0.2, 0.4, -0.6]
    })
    
    # 生成结果列(或直接替换原col1)
    df['col1'] = df[['col1', 'col2']].max(axis=1)
    

    最终输出:

    col1  col2
    0   0.4  -0.9
    1   0.2  -0.5
    2   0.2   0.2
    3   0.4   0.4
    4   0.8  -0.6
    
  • 方法二:用Numpy的where条件判断
    显式判断col1是否为正,是则保留col1,否则取col2:

    import numpy as np
    
    df['col1'] = np.where(df['col1'] > 0, df['col1'], df['col2'])
    

    该方法逻辑更直观,同样是vectorized操作,效率和方法一接近。

  • 不推荐的方法:逐行apply
    虽然df.apply(lambda x: x['col1'] if x['col1']>0 else x['col2'], axis=1)也能实现,但它是逐行处理,在数据量较大时效率远低于前两种方法,不建议使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 03:05:24