如何基于多条件更新DataFrame行中的Hike_percentage值
薪资涨幅修正问题
需求说明
现有包含Employee、Previous_ctc、Current_ctc、Hike_percentage字段的DataFrame,部分Hike_percentage值被错误设为0。需要仅对满足以下所有条件的行修正该字段:
Hike_percentage为0Current_ctc不为0Current_ctc与Previous_ctc不相等
修正公式:((Current_ctc - Previous_ctc) / Previous_ctc) * 100,结果保留一位小数。
示例数据
| Employee | Previous_ctc | Current_ctc | Hike_percentage |
|---|---|---|---|
| 1 | 5000 | 10000 | 100 |
| 2 | 15000 | 20000 | 0 |
| 3 | 16000 | 18000 | 0 |
| 4 | 20000 | 20000 | 0 |
期望输出
| Employee | Previous_ctc | Current_ctc | Hike_percentage |
|---|---|---|---|
| 1 | 5000 | 10000 | 100 |
| 2 | 15000 | 20000 | 33.3 |
| 3 | 16000 | 18000 | 12.5 |
| 4 | 20000 | 20000 | 0 |
错误代码分析
用户尝试的代码存在多处问题:
- 错误地对单个列
Current_ctc调用apply,此时lambda参数x是列的单个数值,无法访问Previous_ctc等其他字段 - 语法混乱:
round函数的参数写法错误,条件判断逻辑不符合Python语法,还出现了未定义的字段Final Fixed Compensation
正确解决方案
方法1:向量化布尔索引(推荐,效率更高)
利用pandas的向量化操作定位目标行,直接计算赋值:
# 构建布尔条件,筛选需要修正的行 mask = (df['Hike_percentage'] == 0) & (df['Current_ctc'] != 0) & (df['Current_ctc'] != df['Previous_ctc']) # 计算涨幅并保留一位小数,赋值回原字段 df.loc[mask, 'Hike_percentage'] = round( ((df.loc[mask, 'Current_ctc'] - df.loc[mask, 'Previous_ctc']) / df.loc[mask, 'Previous_ctc']) * 100, 1 )
方法2:逐行apply处理(适合复杂逻辑场景)
如果需要处理更复杂的逐行判断,可指定axis=1让apply作用于整行:
def fix_hike_percentage(row): # 检查所有修正条件 if row['Hike_percentage'] == 0 and row['Current_ctc'] != 0 and row['Current_ctc'] != row['Previous_ctc']: return round(((row['Current_ctc'] - row['Previous_ctc']) / row['Previous_ctc']) * 100, 1) # 不满足条件则返回原数值 return row['Hike_percentage'] # 应用函数到每一行 df['Hike_percentage'] = df.apply(fix_hike_percentage, axis=1)
两种方法运行后,均可得到符合期望的输出结果。
内容的提问来源于stack exchange,提问作者technical
相关产品推荐
相关产品推荐

