python - 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.
解决方案
将 csv 转换为数据框(df.to_csv(header=True))
以从第二行开始索引
iloc
然后,在函数中
传递行/记录号以使用( df.iloc[ 3 , : ])
推荐阅读
- c# - 差两个双数的错误结果
- python - 尝试使用热图添加颜色条时出现 AttributeError
- multithreading - 使用 dask 并行读取文件
- r - 从 corres.fnc 数据绘制的基本图中缺少一些内部文本
- php - 如何在 WordPress/WooCommerce 3+ 中向评论表单添加自定义字段
- php - 如何通过添加最后一条记录来获得分组?
- html - Z-index 属性无法按预期将菜单始终放在其他 div 元素的顶部
- javascript - 在网页上看不到特定资源
- c# - 将列标题与从 c# 中的 datagridview 导出的文本文件中的单元格值对齐
- ruby-on-rails - 在层次结构中获取孩子、孙子