读取CSV时分组行
我有一个CSV格式的报告,其中有一部分是分组的数据。
也就是说,在某个时刻,我想同时处理两行数据。
0. headers,,,,
1. regular data,,,,
2. regular data,,,,
3. batched_data_a, 0,1,2,3
4. batched_data_a, 4,5,6,7
5. batched_data_b, 0,1,2,3
6. batched_data_b, 4,5,6,7
7. batched_data_c, 0,1,2,3
8. batched_data_c, 4,5,6,7
我在想有没有人有什么好办法。
现在我能想到的就是用 for idx, row in enumerate( csvreader ):
这个方式,然后用索引来关联数据。不知道有没有其他的建议。
3 个回答
0
假设你手里的数据第一列是匹配的,比如说如果'batched_data_a'后面跟着'batched_data_a',那么它们就是一对。你可以把文件分成一行一行的列表,再把每一行分成一个个单词的列表,然后用索引来逐个查看。
我说的意思大概是这样的:
lines = file_name.splitlines()
split_lines = []
for lin in lines:
split_lines.append(lin.split(","))
这样你就得到了一个列表的列表:每一行现在都是一个用逗号分开的值的列表,而整个文件就是一个行的列表。接下来,你可以通过检查相邻的行是否匹配,来获取你想要的元组。
tuple_list = []
for i in range(0, len(split_lines) - 1):
this_line = split_lines[i]
next_line = split_lines[i+1]
if this_line[0] == next_line[0]:
k = 1
while k < 5:
a = this_line[k]
b = next_line[k]
tuple_list.append((this_line[0], a, b))
k += 1
这不是最快的方法,但因为我无法在你的数据集上测试,所以我觉得简单的解决方案也不错。
1
我最后创建了一个自定义类来处理这个文件,并使用了生成器(就像https://stackoverflow.com/users/1388392/m-wasowski建议的那样)来管理每个部分。
我可能应该使用https://stackoverflow.com/users/408426/rumple-stiltskin提到的行组合(这个主意真不错),但我已经写好了消费者代码。所以我在源代码中标记了那个答案,以便有时间重写的时候再去参考!
class CustomFile(object):
def __init__(self, csvdata):
self.csvdata = csvdata
@property
def header( self ):
reader = csv.reader( self.csvdata[0:3] )
for row in reader:
yield row
@property
def body( self ):
reader = csv.reader( self.csvdata[3:] )
for l1 in reader :
if not any(l1):
raise StopIteration()
l2 = reader.next()
yield l1, l2
csvdata = open('data.csv', 'r').readlines()
csvdata = [i.strip() for i in csvdata ]
customFile = CustomFile( csvdata )
print [ i for i in customFile.header ]
print [ i for i in customFile.body ]
1
这个对你有用吗?
#!/usr/bin/env python
import csv
cr = csv.reader(file("test.csv"))
while True:
try:
row1, row2 = cr.next(), cr.next()
row = [row1[0]] + row1[1:] + row2[1:]
except StopIteration:
break
print row