gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:36:07 26 4
gpt4 key购买 nike

每次“通话解析时间”列中出现新月份时,我都希望使用该月份和年份创建一个新的 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,仅包含2015年5月XX日的数据

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

最佳答案

尝试以下操作,

# 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)

如果有问题请发表评论。

关于python - 按月份过滤 CSV 并使用该月份的数据创建新的 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37191808/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com