首页 > 解决方案 > Python:如何从 csv 文件的第二行开始每隔三行迭代一次

问题描述

我正在尝试编写一个程序,逐行遍历 csv 文件的长度。它将创建 3 个新的 csv 文件并将源 csv 文件中的数据写入每个文件。该程序对 csv 文件的整个行长度执行此操作。

对于第一个 if 语句,我希望它从第一行开始每隔三行复制一次并将其保存到一个新的 csv 文件中(它复制的下一行将是第 4 行、第 7 行、第 10 行等)

对于第二个 if 语句,我希望它从第二行开始每隔三行复制一次并将其保存到一个新的 csv 文件中(它复制的下一行将是第 5 行、第 8 行、第 11 行等)。

对于第三个 if 语句,我希望它从第三行开始每隔三行复制一次并将其保存到一个新的 csv 文件中(它复制的下一行将是第 6 行、第 9 行、第 12 行等)。

我写的第二个“if”语句创建了第一个“agentList1.csv”,它完全按照我想要的方式工作,但我不知道如何让第一个“elif”语句从第二行和第二行开始“elif”语句从第三行开始。任何帮助将非常感激!

这是我的代码:

for index, row in Sourcedataframe.iterrows(): #going through each row line by line

#this for loop counts the amount of times it has gone through the csv file. If it has gone through it more than three times, it resets the counter back to 1.
for column in Sourcedataframe: 
    if count > 3:
        count = 1

        #if program is on it's first count, it opens the 'Sourcedataframe', reads/writes every third row to a new csv file named 'agentList1.csv'.
    if count == 1:
        with open('blankAgentList.csv') as infile: 

          with open('agentList1.csv', 'w') as outfile:
            reader = csv.DictReader(infile)
            writer = csv.DictWriter(outfile, fieldnames=reader.fieldnames)
            writer.writeheader()
            for row in reader:
                count2 += 1
                if not count2 % 3:
                    writer.writerow(row)

    elif count == 2:
        with open('blankAgentList.csv') as infile:

          with open('agentList2.csv', 'w') as outfile:
            reader = csv.DictReader(infile)
            writer = csv.DictWriter(outfile, fieldnames=reader.fieldnames)
            writer.writeheader()
            for row in reader:
                count2 += 1
                if not count2 % 3:
                    writer.writerow(row)

    elif count == 3:
        with open('blankAgentList.csv') as infile:

          with open('agentList3.csv', 'w') as outfile:
            reader = csv.DictReader(infile)
            writer = csv.DictWriter(outfile, fieldnames=reader.fieldnames)
            writer.writeheader()
            for row in reader:
                count2 += 1
                if not count2 % 3:
                    writer.writerow(row)

    count = count + 1 #counts how many times it has ran through the main for loop. 

标签: pythonexcelpandascsv

解决方案


将 csv 转换为数据框(df.to_csv(header=True))以从第二行开始索引

iloc然后,在函数中 传递行/记录号以使用( df.iloc[ 3 , : ])


推荐阅读