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

基于DataFrame的label列执行指定数学运算的实现求助

解决方案:根据DataFrame的label列计算result列

首先定义原始DataFrame:

import pandas as pd

data = {'label':['y', 'x', 'z', 'y', 'z', 'x' ],
        'x_score': [0.35, 0.7, 0.05, 0.12, 0.2, 0.9],
         'y_score': [0.6, 0.2, 0.45, 0.58, 0.3, 0.05],
         'z_score': [0.05, 0.1, 0.5, 0.3, 0.5, 0.05]} 

df = pd.DataFrame(data)

需求说明

根据label列的值计算新列result:

  • 当label为x时,直接取x_score的值
  • 当label为z时,取z_score的负值(-z_score)
  • 当label为y时,计算x_score - y_score的结果

方法1:使用numpy.select(推荐,高性能)

numpy.select适合多条件分支场景,相比apply性能更优,尤其适用于大数据集:

import numpy as np

# 定义条件列表
conditions = [
    df['label'] == 'x',
    df['label'] == 'z',
    df['label'] == 'y'
]

# 对应条件的结果计算逻辑
values = [
    df['x_score'],
    -df['z_score'],
    df['x_score'] - df['y_score']
]

# 生成result列,保留两位小数
df['result'] = np.select(conditions, values).round(2)

# 输出结果
print(df)

输出结果:

label  x_score  y_score  z_score  result
0     y     0.35     0.60     0.05    0.30
1     x     0.70     0.20     0.10    0.70
2     z     0.05     0.45     0.50   -0.50
3     y     0.12     0.58     0.30   -0.18
4     z     0.20     0.30     0.50   -0.50
5     x     0.90     0.05     0.05    0.90

方法2:使用apply(代码直观,小数据集适用)

如果数据集规模较小,使用apply逐行处理代码更直观:

def get_result(row):
    if row['label'] == 'x':
        return row['x_score']
    elif row['label'] == 'z':
        return -row['z_score']
    elif row['label'] == 'y':
        return row['x_score'] - row['y_score']

df['result'] = df.apply(get_result, axis=1).round(2)

方法3:字典映射+lambda

通过字典定义每个label对应的计算逻辑,再结合apply实现:

label_calculations = {
    'x': lambda r: r['x_score'],
    'z': lambda r: -r['z_score'],
    'y': lambda r: r['x_score'] - r['y_score']
}

df['result'] = df.apply(lambda r: label_calculations[r['label']](r), axis=1).round(2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:36:42