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

Pandas遍历CSV处理IP列时出现单位置索引器越界错误如何解决

问题原因与解决方案

错误触发根因

  • 循环内部错误覆盖了原始输入的DataFrame变量:第一次循环执行到df = pd.DataFrame(columns=[DN, cidr, country, date, network])时,存储了所有主机记录的原始df就被替换为一个空的、仅包含列名的新DataFrame,第二次循环尝试读取第二条记录时,新df没有对应行数据,直接触发越界错误。
  • 混用行标签与位置索引:iterrows()返回的第一个值是DataFrame的行标签,不是从0开始的连续行位置号,iloc要求传入行位置号,当原始df索引不连续时也会触发该错误。

修正后代码

import socket
import time
import pandas as pd
from ipwhois import IPWhois

def whoisyou(df):
    s = socket.socket()
    s.settimeout(10)
    # 首次写入控制是否写表头
    write_header = True
    for _, row in df.iterrows():
        # 直接从row对象取ip列,无需iloc
        dn = row["ip"]
        try:
            ipwhois = IPWhois(dn).lookup_rdap(asn_methods=["dns", "whois", "http"])
            # 构造单行结果字典
            res = {
                "ip": dn,
                "asn_description": ipwhois["asn_description"],
                "asn_country_code": ipwhois["asn_country_code"],
                "asn_date": ipwhois["asn_date"],
                "asn_cidr": ipwhois["asn_cidr"]
            }
            # 单次写入单行,控制表头只写一次
            pd.DataFrame([res]).to_csv("output.csv", index=False, mode="a", header=write_header)
            if write_header:
                write_header = False
            time.sleep(5)
        except Exception as e:
            print(f"IP {dn} 查询失败:{str(e)}")
            continue

优化说明

  • 删除了对原始df变量的重写逻辑,避免原始数据被覆盖
  • 直接从iterrows()返回的row对象中读取ip列,规避索引混用问题
  • 新增表头写入控制,避免追加写csv时重复生成表头
  • 新增异常捕获逻辑,单条IP查询失败不会终止整个遍历流程

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:15:00