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

Python中如何通过循环处理DataFrame多列以简化重复代码

循环实现版本

直接遍历1~12的序号,动态拼接列名即可复用逻辑:

# 第一个条件:处理P列
for idx in range(1, 13):
    p_col = f"P{idx}"
    t_col = f"T{idx}"
    df[p_col] = df.apply(lambda row: 1 if row[p_col] >= 5 * row[t_col] else 0, axis=1)

# 第二个条件:处理T列
for idx in range(1, 13):
    t_col = f"T{idx}"
    df[t_col] = df.apply(lambda row: 1 if row[t_col] >= 7 else 0, axis=1)

# 第三个条件:生成G列
for idx in range(1, 13):
    p_col = f"P{idx}"
    t_col = f"T{idx}"
    g_col = f"G{idx}"
    df[g_col] = np.where((df[t_col]==1) & (df[p_col]==1), 1, 0)

更高性能的优化版本

原代码里的apply是逐行遍历,数据量大的时候效率很低,完全可以替换为Pandas向量化操作,不需要用apply,写法更简洁速度也更快:

for idx in range(1, 13):
    p_col = f"P{idx}"
    t_col = f"T{idx}"
    # 第一个条件逻辑
    df[p_col] = (df[p_col] >= 5 * df[t_col]).astype(int)
    # 第二个条件逻辑
    df[t_col] = (df[t_col] >= 7).astype(int)
    # 第三个条件逻辑
    df[f"G{idx}"] = ((df[t_col] == 1) & (df[p_col] == 1)).astype(int)

这个版本把三个逻辑合并到了一个循环里,也可以拆成三个独立循环,执行结果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 05:36:04