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

标签 python-3.x networking decode networkx social

我正在尝试从 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/

相关文章:

networking - 嵌入式 IP 堆栈 : is it okay/accepted to have asynchronous sending?

Javascript解码URI会出现问题

php - file_get_contents(JSON) 不适用于有效的 URL

python - 使用 Python 3.5 安装 Seaborn 时出错

python-3.x - 具有包含重复项的元组的 Python3 排列

python - 如何使用 scapy 欺骗 UDP 数据包中的 IP 地址

android - h264 原始视频流格式

python - 为什么要使用 __prepare__ 方法来获取类的命名空间?

python-3.x - 使用 chmod +x 更改 python 文件权限

networking - UDP有效负载长度和数据包传输