如何基于Pandas DataFrame的一列计算转换另一列的取值?
你的代码没有生效的核心原因有两个:
- 计算得到的转换后bonus值仅做了打印,没有赋值回DataFrame的Bonus列,原始数据不会被修改
- 原有逻辑未处理带'-'的区间格式Bonus值,无法覆盖所有规则要求的场景
修改后的循环版本(基于你的原有逻辑调整)
def convertToNumber(df): # 先把Total列转成整数类型,方便后续计算 df['Total'] = df['Total'].astype(int) for i in df.index: bonus_raw = df.loc[i, 'Bonus'] # 处理区间格式:拆分后取最小值 if '-' in bonus_raw: bonus_raw = bonus_raw.split('-')[0].strip() # 转换逻辑 if bonus_raw == '0': bonus = 0 elif bonus_raw.endswith('k'): num = float(bonus_raw.replace('k','')) bonus = int(num * 1000) elif bonus_raw.endswith('%'): rate = float(bonus_raw.replace('%','')) total = df.loc[i, 'Total'] bonus = int(total * rate // 100) else: bonus = -1 # 核心:把计算结果写回DataFrame df.loc[i, 'Bonus'] = bonus convertToNumber(df) print(df)
更推荐的Pandas向量化写法(性能更好,符合Pandas使用习惯)
def convert_single(bonus_raw, total): # 单条数据转换逻辑 if '-' in bonus_raw: bonus_raw = bonus_raw.split('-')[0].strip() if bonus_raw == '0': return 0 elif bonus_raw.endswith('k'): return int(float(bonus_raw.replace('k','')) * 1000) elif bonus_raw.endswith('%'): rate = float(bonus_raw.replace('%','')) return int(int(total) * rate // 100) return -1 # 逐行应用转换逻辑,直接覆盖原Bonus列 df['Bonus'] = df.apply(lambda row: convert_single(row['Bonus'], row['Total']), axis=1)
两种写法运行后都能得到你要求的目标DataFrame结果。
内容的提问来源于stack exchange,提问作者dorothyZhang
相关产品推荐
相关产品推荐

