【问题标题】:How to create an array from a csv file in python [closed]如何在python中从csv文件创建数组[关闭]
【发布时间】:2016-09-26 04:46:12
【问题描述】:

我有一个包含如下列表的 csv 文件:

12、1233、234

12、1233、989

12、9898、213

14、1233、987

14、1233、876

我想为相似的行创建一个数组。例如在上面的例子中,我想创建一个这样的数组: 12, 1233 [234, 989] 因为它们的前两行中的值是相同的

import csv with open('check.csv', 'r') as csvfile: 
    reader = csv.reader(csvfile, delimiter=',') for row in reader:
         print(re.search( #uniqueSet = list(set(x)) 

【问题讨论】:

  • 听起来你需要写一些代码,那么。你有问题吗?
  • import csv with open('check.csv', 'r') as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: print(re.search (#uniqueSet = list(set(x)) 在那里被击中
  • edit问题显示minimal reproducible example; “卡住”是什么意思?
  • 只有一个像12、9898、213这样的行,你要还是不要?
  • @Merlin 啊,在移动应用中看不到,抱歉。

标签: python arrays csv


【解决方案1】:

这段代码将为您完成大部分工作

#read the csv file
with open('csv_file.csv','r') as f:
   lines=[l.split(',') for l in f.readlines()]
#Aggregate by the 3rd field by the first two fields
import collections    
d=collections.defaultdict(list)
for l in lines:
   d[(l[0],l[1])].append(l[2])

csv (csv_file.csv) 文件将被读取为字典(变量 d),您只需将其转换为列表或任何您想要的格式

【讨论】:

  • import csv import collections with open('file.csv','r') as f: #lines=[l.split(',') for l in f.readlines()] 阅读器= [l.split(',') for l in f.readlines()] d=collections.defaultdict(list) for l in reader: d[l[0]+':'+l[1]].append (l[2]) uniqueSet = list(set(l)) print(d) 这行得通!
  • 如果我的回答有帮助,请接受或至少投票
  • 嗨,是的!我接受了它,但我无法投票,因为我需要 15 分才能投票.. :)
猜你喜欢
  • 1970-01-01
  • 2015-01-04
  • 1970-01-01
  • 1970-01-01
  • 2011-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-26
相关资源
最近更新 更多