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

Python读取CSV全部字段时NetworkX add_edge报错的解决问询

解决NetworkX添加带属性边的TypeError问题

你的报错TypeError: Graph.add_edge() takes 3 positional arguments but 4 were given,本质是NetworkX的add_edge方法参数使用错误:该方法仅接受前两个位置参数作为边的两个节点,后续的边属性必须以关键字参数或属性字典的形式传递,不能直接传位置参数。

针对你的CSV数据,提供两种可行的修复方案:

方案1:修正add_edge参数传递方式

直接修改原代码中添加边的行,将genre作为关键字参数传入,同时用.strip()清理字段中的换行符或空格:

def read_net(filename):
    g = nx.Graph()
    with open(filename,encoding="ISO-8859-1",newline="") as f:
        f.readline()
        for l in f:
            l = l.strip().split(",")  # 先整行去除首尾空白再分割
            # 用关键字参数传递genre属性
            g.add_edge(l[0].strip(), l[1].strip(), genre=l[2].strip())
    return g

read_net("edge.csv")

方案2:用csv模块规范读取CSV(更推荐)

手动用split(",")分割CSV存在潜在风险(比如字段包含逗号时会出错),使用Python内置的csv模块读取更可靠:

import csv
import networkx as nx

def read_net(filename):
    g = nx.Graph()
    with open(filename, encoding="ISO-8859-1", newline="") as f:
        # DictReader自动将首行作为字段名,每行返回字典格式数据
        reader = csv.DictReader(f)
        for row in reader:
            # 提取并清理字段值
            source = row["source"].strip()
            target = row["target"].strip()
            # 若genre是数值类型,可转换为int/float
            genre = int(row["genre"].strip())
            # 添加带属性的边
            g.add_edge(source, target, genre=genre)
    return g

read_net("edge.csv")

额外说明

如果你的genre字段需要数值类型(如示例中的28、30),记得将字符串转换为int或float,这样后续对属性进行计算或分析时会更方便。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 03:20:17