Python中For循环未按预期迭代,处理DataFrame生成多余条目的问题
问题原因
- 结果数量翻倍:
你的df_enlaces中同一个邮箱对应2条数据,外层for循环遍历所有行时会执行2次,每次循环到同一个邮箱时,set_index('CorreoElectronico').loc[user]会返回该邮箱对应的全部2条链接序列,内层while循环会执行2次,2次外层循环 * 2次内层循环最终得到4条结果。 - 链接取值错误:
你在内层拼接HTML时使用外层循环的索引arch取链接值,第一次外层循环arch=0,两次内层循环都取enlace[0]也就是link1;第二次外层循环arch=1,两次内层循环都取enlace[1]也就是link2,最终得到两个link1、两个link2的重复结果。
另外你原代码中按钮的style属性写法有误,分号应该放在style的引号内部。
修复方案
不需要嵌套循环,直接逐行遍历DataFrame即可,一行数据对应一个链接按钮:
boton_list = [] for _, row in df_enlaces.iterrows(): enlace = row['Enlace'] boton = f"""<a href="{enlace}" > <button style='background-color: orange; border-color:blue'> LINK </button> </a>""" boton_list.append(boton)
如果需要按邮箱分组,把同一用户的所有链接集中处理,可以用groupby实现:
boton_list = [] # 按邮箱分组处理 for user, group in df_enlaces.groupby('CorreoElectronico'): # 遍历该用户的所有链接生成按钮 for enlace in group['Enlace']: boton = f"""<a href="{enlace}" > <button style='background-color: orange; border-color:blue'> LINK </button> </a>""" boton_list.append(boton)
内容的提问来源于stack exchange,提问作者alb
相关产品推荐
相关产品推荐

