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

Pandas遍历DataFrame列值输出重复,求正确打印员工汇报信息的方法

问题解决

现有DataFrame:

emp_idemp_rolemgr_idmgr_role
111AP112SP
112SP116DP
114LP115DP

原代码的问题是循环emp_id列时,每次拼接的都是整个emp_role、mgr_id等列,而非当前行对应的值,导致输出重复。以下是几种正确实现方式:

方法1:迭代DataFrame的行

用iterrows()遍历每一行,直接获取当前行的各个字段值:

for idx, row in df.iterrows():
    print(f"{row['emp_id']} with role {row['emp_role']} is reporting to {row['mgr_id']} with role {row['mgr_role']}")

方法2:用apply逐行处理

通过apply对每一行执行打印操作,适合更灵活的行处理场景:

def print_report(row):
    print(f"{row['emp_id']} with role {row['emp_role']} is reporting to {row['mgr_id']} with role {row['mgr_role']}")

df.apply(print_report, axis=1)

方法3:循环索引(适合小型数据集)

通过索引定位每一行的对应值,逻辑直观易懂:

for i in range(len(df)):
    emp_id = df.iloc[i]['emp_id']
    emp_role = df.iloc[i]['emp_role']
    mgr_id = df.iloc[i]['mgr_id']
    mgr_role = df.iloc[i]['mgr_role']
    print(f"{emp_id} with role {emp_role} is reporting to {mgr_id} with role {mgr_role}")

以上三种方法都能输出期望结果:

111 with role AP is reporting to 112 with role SP
112 with role SP is reporting to 116 with role DP
114 with role LP is reporting to 115 with role DP

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 02:20:49