我有一个包含2列的CSV文件:用户和位置。我想创建两个列表:一个只有用户,另一个只有位置,所以我可以使用networkx中的draw_network_nodes(nodelist = ...)函数分别绘制用户和位置作为具有不同形状和颜色的节点(所有用户)将是蓝色框,所有位置将是红色圆圈)。
此外,我的CSV文件中有一个标题,因此我不希望标题名称成为任何列表的一部分。
答案 0 :(得分:1)
由于您没有提供任何输入,预期输出,我对它们做了一些假设。假设输入文件名为 data.csv :
user,location
john,seattle
alan,los angeles
trish,new york
将csv拆分为两个文件的脚本称为 csv_split.py :
import csv
with open('data.csv') as csv_in, \
open('users.txt', 'w') as users_out, \
open('locations.txt', 'w') as locations_out:
csv_dict_reader = csv.DictReader(csv_in)
for line in csv_dict_reader:
users_out.write(line['user'] + '\n')
locations_out.write(line['location'] + '\n')
答案 1 :(得分:0)
建立在Hai Vu的回答之上:
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
给出:
locations = ('seattle', 'los angeles', 'new york', 'london')
users = ('john', 'alan', 'trish', 'jack')
自:
user,location
john,seattle
alan,los angeles
trish,new york
jack,london