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

如何在Pandas中根据sum和bid列的行条件计算佣金?

计算Pandas DataFrame中的佣金列

原始数据结构

id_trancsumbid
140002.3%
1200003.5%
2100000若sum≥100000则1.6%,若sum<100000则100$
330000若sum≥100000则1.6%,若sum<100000则100$
160000500$

创建数据集的代码:

import pandas as pd

dataframe = pd.DataFrame({
    'id_tranc': [1, 1, 2, 3, 1],
    'sum': [4000, 20000, 100000, 30000, 60000],
    'bid': ['2.3%', '3.5%', 'if >=100 000 - 1.6%, if < 100 000 - 100$', 'if >=100 000 - 1.6%, if < 100 000 - 100$', '500$']
})

目标结果

需计算commission列,最终DataFrame如下:

id_trancsumbidcommission
140002.3%92
1200003.5%700
2100000若sum≥100000则1.6%,若sum<100000则100$1600
330000若sum≥100000则1.6%,若sum<100000则100$100
160000500$500

问题分析

直接执行df['commission'] = df['sum'] * df['bid']仅前两行有效,因为bid列包含三种不同格式的字符串:纯百分比、固定金额、条件表达式,无法直接进行数值运算。

解决方案

针对不同bid格式分别处理,通过自定义函数结合apply方法实现:

def calculate_commission(row):
    bid = row['bid']
    sum_val = row['sum']
    
    # 处理纯百分比格式(如2.3%)
    if '%' in bid and 'if' not in bid:
        rate = float(bid.replace('%', '')) / 100
        return sum_val * rate
    # 处理固定金额格式(如500$)
    elif '$' in bid and 'if' not in bid:
        return float(bid.replace('$', ''))
    # 处理条件表达式格式
    elif 'if' in bid:
        # 拆分条件片段
        parts = bid.split(',')
        # 提取>=100000对应的费率
        rate_part = parts[0].split('-')[-1].strip()
        rate = float(rate_part.replace('%', '')) / 100
        # 提取<100000对应的固定金额
        amount_part = parts[1].split('-')[-1].strip()
        fixed_amount = float(amount_part.replace('$', ''))
        # 根据sum值判断计算逻辑
        return sum_val * rate if sum_val >= 100000 else fixed_amount

# 应用函数生成commission列
dataframe['commission'] = dataframe.apply(calculate_commission, axis=1)

# 查看最终结果
print(dataframe)

运行上述代码后,即可得到目标中的commission列结果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 01:57:03