Python搜索列

时间:2016-10-12 21:53:06

标签: python loops csv

我有一个CSV文件,我需要以特定模式为特定列循环,并将输出模式存储在具有相同名称+“_pattern”+ [1,2,3等]的新文件中+ .csv。

这是搜索模式:遍历第1列并找到相同的#并抓住它们,然后遍历抓取列表的第2列,然后获取第2列中具有相同日期的所有内容,然后转到第4列,抓住所有不相同的#s,然后创建一个文件,其中第1列和第2列的模式按列时间组织。

示例:

1       2           time    4
13.45   9/29/2016   6:00    98765
12.56   9/29/2016   6:05    76548
13.45   9/29/2016   6:07    98764
13.45   9/29/2016   6:21    98766
13.45   9/29/2016   6:20    96765
12.56   9/29/2016   6:06    76553

Better view of table

结果是,file_pattern_1.csv将具有:

1. 13.45    9/29/2016   6:00    98765
2. 13.45    9/29/2016   6:07    98764
3. 13.45    9/29/2016   6:21    98766

但不包括:

4. 13.45    9/29/2016   6:20    96765 

因为第4列从前一个条目重复,所以file_pattern_2.csv将具有:

1. 12.56    9/29/2016   6:05    76548
2. 12.56    9/29/2016   6:06    76553

这是我到目前为止所做的,但我已经迷失在循环逻辑上:

import os

infile = raw_input("Which file are we working with? ")
assert os.path.exists(infile), "Path is incorrect."
os.chdir(infile)

def createFile(csvFile, fileName):
    with open (fileName, 'wb') as ftext:
        ftext.write(csvFile)

def appendFile(csvFile, fileName):
    with open (fileName, 'a') as ftext:
        ftext.write(csvFile)

def setfilename(tread):
    fileName = tread[0:tread.index('.')] + '_patterns' + str(countItem) + '.csv'
    return fileName

for i in pcolumn:
    if pcolumn == pcolumn:
        return pfile
    for x in date:
        if date == date:
            return date
            for a in acolumn:
                if acolumn != acolumn:
                    createFile(fileName)
else:
    print "Finished."

2 个答案:

答案 0 :(得分:1)

当您循环浏览文件时,您需要记录哪些模式不符合保存条件。您可以使用set来实现此目的。要在每个文件中对条目进行分组,您可以使用itertools.groupby。使用您的示例:

import itertools

f = [i.split("   ") for i in """1       2           time    4
13.45   9/29/2016   6:00   98765
12.56   9/29/2016   6:05   76548
13.45   9/29/2016   6:07   98764
13.45   9/29/2016   6:21   98766
13.45   9/29/2016   6:20   96765
12.56   9/29/2016   6:06   76553""".split("\n")[1:]]


seen_patterns = set([('9/29/2016', '96765')])   # You need to add entries to this set which you want to exclude

# Sort and group your entries by the first and second columns
col1 = itertools.groupby(sorted(f, key=lambda x: (x[0], x[1])), key=lambda x: (x[0], x[1]))
for k, v in col1:
    v = list(v)
    # Filter out patterns which are not allowed
    to_save = [" ".join(i) for i in v if (i[1], i[3]) not in seen_patterns]
    for i in to_save:
        print i  # Save this to an appropriate file
    print

>>>
12.56 9/29/2016 6:05 76548
12.56 9/29/2016 6:06 76553

13.45 9/29/2016 6:00 98765
13.45 9/29/2016 6:07 98764
13.45 9/29/2016 6:21 98766

作为进一步的建议,看一下用于从目录中收集文件路径的glob模块,它非常有用。

答案 1 :(得分:1)

以下应该做你需要的。它读取csv文件并为每个条目生成匹配的datetime,以允许它们正确排序。它根据模式编号创建输出csv文件,条目按日期排序。已经看到的第4列条目被省略:

from itertools import groupby
from datetime import datetime
import csv
import os

filename = 'my_data.csv'
data = []

with open(filename, 'rb') as f_input:
    csv_input = csv.reader(f_input, delimiter='\t')
    header = next(csv_input)

    for row in csv_input:
        dt = datetime.strptime('{} {}'.format(row[2], row[1]), '%H:%M %m/%d/%Y')
        data.append([dt] + row)

for index, (k, g) in enumerate(groupby(sorted(data, key=lambda x: x[1]), key=lambda x: x[1]), start=1):
    line = 1
    seen = set()

    with open('{}_pattern_{}.csv'.format(os.path.splitext(filename)[0], index), 'wb') as f_output:
        csv_output = csv.writer(f_output)

        for item in sorted(g, key=lambda x: x[0]):
            if item[4] not in seen:
                seen.add(item[4])
                csv_output.writerow([line] + item[1:])
                line += 1