如何在Pandas中根据sum和bid列的行条件计算佣金?
计算Pandas DataFrame中的佣金列
原始数据结构
| id_tranc | sum | bid |
|---|---|---|
| 1 | 4000 | 2.3% |
| 1 | 20000 | 3.5% |
| 2 | 100000 | 若sum≥100000则1.6%,若sum<100000则100$ |
| 3 | 30000 | 若sum≥100000则1.6%,若sum<100000则100$ |
| 1 | 60000 | 500$ |
创建数据集的代码:
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_tranc | sum | bid | commission |
|---|---|---|---|
| 1 | 4000 | 2.3% | 92 |
| 1 | 20000 | 3.5% | 700 |
| 2 | 100000 | 若sum≥100000则1.6%,若sum<100000则100$ | 1600 |
| 3 | 30000 | 若sum≥100000则1.6%,若sum<100000则100$ | 100 |
| 1 | 60000 | 500$ | 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
相关产品推荐
相关产品推荐

