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

通过循环与条件为现有DataFrame新增列时结果未写入问题求助

问题根因

你写的嵌套循环逻辑存在错误:内层遍历每行Join Date和Present Basic值时,直接对contr_calc_new[a]整列赋值,最终每列的值只会保留最后一行遍历的计算结果,完全没有实现按行匹配条件计算的效果。

优化实现方案

不要用嵌套循环处理DataFrame行数据,直接用pandas向量化操作即可,不仅逻辑清晰,运行速度也远快于循环写法:

  1. 先预处理生成统一格式的入职年月临时列,避免重复计算
  2. 遍历每个待新增的月份列,用np.where做条件判断批量计算
import numpy as np

# 先预处理生成统一格式的入职年月列
contr_calc_new['join_year_month'] = contr_calc_new['Join Date'].dt.strftime('%Y-%m')
# 替换为你实际使用的费率值
rate = 你的实际费率变量

for month_name, month_date in zip(month_data.month_list, month_data.month_range):
    target_month = month_date.strftime('%Y-%m')
    # 向量化条件计算
    contr_calc_new[month_name] = np.where(
        contr_calc_new['join_year_month'] == target_month,
        0,
        ((contr_calc_new['Present Basic'] + (contr_calc_new['Present Basic'] * rate) // 100) * 14 // 100).astype(int)
    )

# 按需删除临时生成的年月列
contr_calc_new.drop('join_year_month', axis=1, inplace=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:15:02