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

对比DataFrame的col1与col2列,新增列标记数值增减状态

没问题,我来帮你搞定这个需求!下面是用Python的pandas库实现的完整解决方案:

对比col1与col2生成col3列的实现方法

我们可以用pandas结合numpy的条件判断来高效完成这个需求,代码简洁且适合处理大数据集:

import pandas as pd
import numpy as np

# 先构造你的目标数据集
data = {
    'name': ['a', 'b', 'c', 'd', 'e', 'f'],
    'col1': [10.3, 11, 20, 6.2, 5.3, 4.5],
    'col2': [10.9, 15, 7.2, 6.2, 5.4, 4.0]
}
df = pd.DataFrame(data)

# 核心逻辑:根据col2和col1的大小关系生成col3
df['col3'] = np.where(df['col2'] > df['col1'], 'increasing',
                     np.where(df['col2'] < df['col1'], 'decreasing', 'no change'))

# 查看最终结果
print(df)

运行后会输出你期望的结果:

name  col1  col2        col3
0    a  10.3  10.9  increasing
1    b  11.0  15.0  increasing
2    c  20.0   7.2  decreasing
3    d   6.2   6.2   no change
4    e   5.3   5.4  increasing
5    f   4.5   4.0  decreasing

代码说明

  • np.where()是numpy的高效条件判断函数,支持嵌套使用,完美适配这种多分支的场景:
    • 第一层判断:如果col2大于col1,标记为increasing
    • 第二层嵌套判断:如果col2小于col1,标记为decreasing
    • 剩下的情况(两列数值相等)自动标记为no change
  • 这种方法比逐行遍历的apply()效率高得多,尤其是处理大型数据集时,能显著节省时间。

如果你的数据集已经是现成的DataFrame,直接跳过构造数据的步骤,执行生成col3的那一行代码就行啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:45:27