从CSV文件中提取列以在NetworkX中用作节点列表 [英] Extract column from CSV file to use as nodelist in NetworkX

查看:961
本文介绍了从CSV文件中提取列以在NetworkX中用作节点列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含2列的CSV文件:用户和位置。我想创建两个列表:一个只有用户,另一个只有位置,因此我可以使用networkx中的draw_network_nodes(nodelist = ...)函数将用户和位置分别绘制为具有不同形状和颜色的节点(所有用户将是蓝色的框,所有的位置将是红色的圆圈)。



另外,我的CSV文件中有一个标题,所以我不希望标题名称成为任一列表的一部分。



  import csv 


def reader(文件名):
for(lineno,line)in enumerate(open(filename)):
if lineno> 0:#skip header
yield line

filename =locations.csv
(users,locations)= zip(*(row for csv.reader(reader(文件名))))
printusers =,users
printlocations =,locations

给出:

  locations =('seattle','los angeles','new york','伦敦')
users =('john','alan','trish','jack')

来自:

 用户,位置
john,西雅图
alan,los angeles
trish,new york
jack,伦敦


I have a CSV file with 2 columns: user and locations. I want to create two lists: one with only users and the other with only locations so that I can use the draw_network_nodes(nodelist=...) function in networkx to draw users and locations separately as nodes with different shapes and colors (all users will be blue boxes and all locations will be red circles).

Also, there is a header in my CSV file, so I do not want the header names to be part of either lists.

解决方案

Building on top of Hai Vu's answer:

import csv
def reader(filename):
    for (lineno, line) in enumerate(open(filename)):
        if lineno > 0: # skip header
            yield line

filename = "locations.csv"
(users, locations) = zip(*( row for row in csv.reader(reader(filename))))
print "users     =", users
print "locations =", locations

Gives:

locations = ('seattle', 'los angeles', 'new york', 'london')
users     = ('john', 'alan', 'trish', 'jack')

From:

user,location
john,seattle
alan,los angeles
trish,new york
jack,london

这篇关于从CSV文件中提取列以在NetworkX中用作节点列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆