gpt4 book ai didi

python-3.x - 从 CSV 文件创建 Networkx Graph

转载 作者:行者123 更新时间:2023-12-05 00:48:20 28 4
gpt4 key购买 nike

我正在尝试从 CSV file 构建 NetworkX 社交网络图。 .我正在使用 Networkx 2.1 和 Python 3
我关注了this post没有运气,因为我不断收到错误:

AttributeError: 'list' object has no attribute 'decode'
我的目标是让权重显示出更厚的边缘以适应更高的权重。
到目前为止,这是我的代码:
import networkx as nx
import csv

Data = open('testest.csv', "r", encoding='utf8')
read = csv.reader(Data)
Graphtype=nx.Graph() # use net.Graph() for undirected graph

G = nx.read_edgelist(read, create_using=Graphtype, nodetype=int, data=(('weight',float),))

for x in G.nodes():
print ("Node:", x, "has total #degree:",G.degree(x), " , In_degree: ", G.out_degree(x)," and out_degree: ", G.in_degree(x))
for u,v in G.edges():
print ("Weight of Edge ("+str(u)+","+str(v)+")", G.get_edge_data(u,v))

nx.draw(G)
plt.show()
有没有更简化的方法来解决这个问题?数据比较简单。
感谢您的帮助!

最佳答案

您误用了 read_edgelist 功能.来自 documentation ,每行需要解析一个字符串,而csv.reader将输入文件中的行解析为字符串列表(例如,202,237,1 -> ['202', '237', '1'])。因此,AttributeError被提出是因为 read_edgelist正在尝试解析 csv.reader 提供的列表, 而它们应该是字符串。

我们可以在不使用 csv 的情况下正确解析输入文件中的图形。模块。但是,我们仍然需要处理不应该解析的输入文件的第一行(标题)。有两种方法。第一种方法使用 next 跳过第一行:

Data = open('test.csv', "r")
next(Data, None) # skip the first line in the input file
Graphtype = nx.Graph()

G = nx.parse_edgelist(Data, delimiter=',', create_using=Graphtype,
nodetype=int, data=(('weight', float),))

第二种方法有点“hacky”:因为第一行以 target 开头, 我们标记字符 t作为输入文件中注释的开头。
Data = open('test.csv', "r")
Graphtype = nx.Graph()

G = nx.parse_edgelist(Data, comments='t', delimiter=',', create_using=Graphtype,
nodetype=int, data=(('weight', float),))

在这两种方法中,我们都必须使用 parse_edgelist而不是 read_edgelist因为输入文件使用 \r换行符。使用 read_edgelist , 文件需要以二进制模式打开,其行被拆分 iff the newlines are either \r\n or \n .因此带有 \r 的输入文件换行符不能拆分成行,因此无法正确解析。

此外,由于您想找到入度和出度,因此应该使用 DiGraph 创建图表。 ,而不是 Graph .

编辑

这里的关键点是跳过输入文件中的标题。我们可以通过首先将输入文件读入 pandas.DataFrame 来实现。 ,然后我们将其转换为图形。
import networkx as nx
import pandas as pd

df = pd.read_csv('test.csv')
Graphtype = nx.Graph()
G = nx.from_pandas_edgelist(df, edge_attr='weight', create_using=Graphtype)

关于python-3.x - 从 CSV 文件创建 Networkx Graph,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49683445/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com