按月过滤CSV并使用该月份数据创建新的csv

时间:2016-05-12 15:49:53

标签: python csv datetime filter

每次有#34;新的月份,请致电解决时间"第I列我想要用该月和年创建一个新的csv文件。并且包含该月份和年份的所有行都将被过滤到新的csv。

像这样:

alldata.csv

Call Resolve Time   Priority    Overall Result
8/6/2015                  P4    F
5/13/2015                 P4    F
4/28/2015                 P4    P
5/13/2015                 P4    F
5/27/2015                 P4    F

alldata.csv 创建的新文件 May-2015.csv 仅包含5 / XX / 2015数据

Call Resolve Time   Priority    Overall Result
    5/13/2015                 P4    F
    5/13/2015                 P4    F
    5/27/2015                 P4    F

到目前为止,我有这个,但我必须手动创建每年和每月的东西:

reader = csv.reader(open(r"alldata.csv"), delimiter=',') 
filtered = filter(lambda p: '5/27/15' == p[1], reader) 
csv.writer(open(r"May-2015.csv",'w'),delimiter=',').writerows(filtered)

编辑---------------------------------------------- -----------------------------

# say, reader is the reader object
# do next(reader) to skip the headings
import csv
from itertools import groupby

reader = csv.reader(open(r"alldata.csv"), delimiter=',')

def by_month (row):
    date = row[7] 
    month = int(date.split("/", 1)[0])
    return month

m_g = groupby(reader, by_month)

for month, group in m_g:
    group = list(group)
    # use a month to month_name map
    with open('{}.csv'.format(month), 'w') as fw:
        w = csv.writer(fw)
        w.writerows(group)

手动添加日期:

def by_month(row):
    date = '5/9/2016'
    month = int(date.split("/", 1)[0])
    return month

1 个答案:

答案 0 :(得分:1)

尝试以下方法,

# say, reader is the reader object
# do next(reader) to skip the headings
from itertools import groupby
def by_month(row):
    date = row[0] 
    month = int(date.split("/", 1)[0])
    return month

m_g = groupby(reader, by_month)

for month, group in m_g:
    group = list(group)
    # use a month to month_name map
    with open('{}.csv'.format(month), 'w') as fw:
        w = csv.writer(fw)
        w.writerows(group)

评论某些内容是否有效。