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

如何使用pandas的iterrows方法打印所有行?解决键重复覆盖问题

问题分析与解决

问题场景

现有birthdays.csv数据如下:

name,email,year,month,day
Vishal,abc@email.com,2002,11,22
Riya,xyz@mail.com,2003,11,22

用户编写代码尝试将数据转为生日字典,代码如下:

import pandas as pd  # 注:原代码遗漏导入语句,实际运行需补充

with open("birthdays.csv", "r") as file:
    data = pd.read_csv(file)
    birthdays_dict = {(row['month'], row['day']): row for (index, row) in data.iterrows()}
print(birthdays_dict)

实际输出仅保留最后一行数据:

{(11, 22): name             Riya
email    xyz@mail.com
year             2003
month              11
day                22
Name: 1, dtype: object}

用户预期获取两行数据,同时希望了解如何用iterrows()正确打印所有行。

原因解释

Python字典的键具有唯一性。你用(row['month'], row['day'])作为字典键,两行数据的月份和日期完全相同(均为(11,22)),遍历到第二行时,新的row会覆盖同一键对应的旧值,最终字典仅保留最后一行数据。

正确实现方法

1. 保留同一天的所有生日数据

若需存储同一天的多人生日,可将字典值设为列表,把同一天的所有数据存入列表:

import pandas as pd

with open("birthdays.csv", "r") as file:
    data = pd.read_csv(file)
    birthdays_dict = {}
    for index, row in data.iterrows():
        key = (row['month'], row['day'])
        # 键不存在时初始化空列表
        if key not in birthdays_dict:
            birthdays_dict[key] = []
        birthdays_dict[key].append(row)

# 格式化打印结果
for date, people in birthdays_dict.items():
    print(f"日期 {date} 的生日:")
    for person in people:
        print(f"  {person['name']} - {person['email']}")

2. 使用iterrows()打印所有行

若仅需逐行打印所有数据,直接遍历iterrows()即可:

import pandas as pd

with open("birthdays.csv", "r") as file:
    data = pd.read_csv(file)
    # index为行索引,row为该行的Series对象
    for index, row in data.iterrows():
        print(f"行索引 {index} 的数据:")
        print(f"姓名:{row['name']},邮箱:{row['email']},生日:{row['year']}-{row['month']}-{row['day']}")
        print("-" * 30)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 10:15:54