简体   繁体   English

将函数应用于 csv 文件中的每一行

[英]Apply function to every line in csv file

I have a function from Vasilis G.'s answer here :在这里有一个来自 Vasilis G. 的回答的函数:

 from datetime import datetime def getTotal(line): dates = list(datetime.strptime(elem, '%Y-%m-%d') for elem in line.split(', ')) total = 0 for i in range(0, len(dates), 2): delta = dates[i+1] - dates[i] if delta.days > 90: total += 2 else: total += 1 return total

I then used:然后我使用了:

with open('dataset.csv','r') as csvfile:  # use with to auto-close file
   for row in csvfile.readlines():  # pin_id
       getTotal(row)  # board_id and section can use defaults
       time.sleep(random.randint(1,3)) # wait 1-3 seconds

And I would like to apply it on every line in my csv file but it's giving me "ValueError : unconverted data remains : 2022-06-03,2021-05-29,2024-06-03,2022-05-29,2026-06-03,2023-05-29,2028-06-03,2024-05-29,2030-06-03,2025-05-29,2032-06-03 which coincide with the first line of my .csv file.我想将它应用于我的 csv 文件中的每一行,但它给了我"ValueError : unconverted data remains : 2022-06-03,2021-05-29,2024-06-03,2022-05-29,2026-06-03,2023-05-29,2028-06-03,2024-05-29,2030-06-03,2025-05-29,2032-06-03与我的 .csv 的第一行一致文件。

FINAL :决赛

from datetime import datetime


def getTotal(line):
    dates = [datetime.strptime(elem.strip(), '%Y-%m-%d') for elem in line.split(',')]
    total = 0
    for i in range(0, len(dates), 2):
        delta = dates[i+1] - dates[i]
        if delta.days > 90:
            total += 2
        else:
            total += 1
    return total

print(getTotal(dates))
with open('dataset.csv','r') as csvfile:  
   for row in csvfile.readlines():  
       getTotal(row)

Try this:尝试这个:

def getTotal(line):
    dates = [datetime.strptime(elem.strip(), '%Y-%m-%d') for elem in line.split(',')]
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM