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

pandas使用for循环遍历DataFrame时仅读取列无法读取全部行如何解决

问题原因

直接对Pandas的DataFrame对象执行for row in original遍历操作时,默认迭代对象是列名,你的csv文件刚好有4列,所以只会循环4次,和数据行数无关,这就是你只能遍历到前4条数据的原因。

修复方案

要遍历DataFrame的行,替换遍历逻辑为使用iterrows()方法即可,该方法会返回(行索引, 行数据对象)的元组,不需要你手动维护rn计数变量,优化后的代码如下:

import pandas as pd
from datetime import datetime

# 你原来的日期匹配函数保留即可,这里省略实现
def date_matchingdob(date_str):
    # 你的原有逻辑
    pass
def date_matchingyob(date_str):
    # 你的原有逻辑
    pass

original = pd.read_csv('csv1.csv')
new = pd.read_csv('csv2.csv')

for rn, row in original.iterrows():
    new.loc[rn, 'listid'] = int(row['listid']) ** 3
    new.loc[rn, 'name'] = row['name']
    new.loc[rn, 'country'] = row['country']
    dateinput = row['dob']
    if date_matchingdob(dateinput):
        new.loc[rn, 'dob'] = datetime.strptime(dateinput, '%d/%m/%Y').strftime('%Y%m%d')
    elif date_matchingyob(dateinput):
        new.loc[rn, 'yearofbirth'] = dateinput

# 不要在循环里重复写文件,全部处理完再保存,性能提升明显
new.to_csv('csv2.csv', index=False)
print(new)

补充说明

  • 如果数据量较大,iterrows()性能一般,你可以换成itertuples()方法遍历,速度会快很多,用法为for row in original.itertuples():,取值时用row.listid、row.dob的格式即可。
  • 更推荐用Pandas向量化操作替代循环处理数据,执行效率会远高于逐行遍历。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 17:06:04