无法在Python中的networkx中加载一个简单的csv [英] unable to load a simple csv in networkx in Python
问题描述
我是Python的一个完全noobie,我想使用networkx软件包学习一个数据集。我不明白这里有什么错误:
我有一个csv,看起来像这样(提取):
['152027','-6167']
['152027','-4982']
['152027','-3810']
['152027','-2288']
['152027','-1253']
['152100','-152100']
['152100' -86127']
可以调用此.csv文件节点
。数字继承人没有特别的意义。它们只是匿名的名字:所以152027是一个人连接到个人-6167,个人-4982等。
我在Python中使用下面的代码
import csv
import networkx as nx
file = csv.reader(open(' ,'rb'),delimiter =',')
G = nx.read_edgelist(file,delimiter =',',nodetype = float,encoding ='utf-8')
G.number_of_nodes()
我得到了悲伤的 Out [71]: 0
我不明白这里有什么问题。
你能帮我吗?
nx.read_edgelist
期望第一个变量是文件句柄或文件名字符串,而不是 csv.reader
对象。
Don不要使用 csv
;尝试只是
G = nx.read_edgelist('nodes',delimiter =',',nodetype = int,encoding =utf -8)
编辑 ,您可以将
作为inf打开('nodes','rb'):
pre>
next '')#跳过一行
G = nx.read_edgelist(inf,delimiter =',',nodetype = int,encoding =utf-8)
I am a complete noobie in Python, and I would like to study a dataset using the networkx package. I do not understand what is wrong here:
I have a csv which looks like this (extract):
['152027', '-6167'] ['152027', '-4982'] ['152027', '-3810'] ['152027', '-2288'] ['152027', '-1253'] ['152100', '-152100'] ['152100', '-86127']
lets call this .csv file
nodes
. Numbers heres have no particular meanings. They are just anonymised names: so 152027 is a person that is connected to individual -6167, individual -4982, etc.I use the following code in Python
import csv import networkx as nx file = csv.reader(open('nodes', 'rb'), delimiter=',') G=nx.read_edgelist(file, delimiter=',',nodetype=float,encoding='utf-8') G.number_of_nodes()
and I get the sad
Out[71]: 0
I do not understand what is wrong here. Could you please help me?解决方案
nx.read_edgelist
expects the first variable to be a file handle or filename string, not acsv.reader
object.Don't use
csv
at all; try justG = nx.read_edgelist('nodes', delimiter=',', nodetype=int, encoding="utf-8")
Edit: if you need to skip a header line, you could do
with open('nodes', 'rb') as inf: next(inf, '') # skip a line G = nx.read_edgelist(inf, delimiter=',', nodetype=int, encoding="utf-8")
这篇关于无法在Python中的networkx中加载一个简单的csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!