[英]How to copy specific rows from csv file to another csv file based on specific column?
Let's suppose that this is my data. 假设这是我的数据。
frame.number frame.len frame.cap_len Packets_Type
1 100 100 ICMP_tt
2 64 64 UDP
3 100 100 ICMP_tt
4 87 64 ICMP_nn
5 100 100 ICMP_tt
6 87 64 ICMP_nn
7 100 100 ICMP_tt
8 87 64 ICMP_nn
9 87 64 ICMP_nn
I put my data in a csv file, I want to extract rows where Packets_Type
is equal to ICMP_tt
我将数据放入一个csv文件中,我想提取出Packets_Type
等于ICMP_tt
import csv
f = open("file.csv", "rb")
reader = csv.DictReader(f, delimiter=',')
writer = open("newfile.csv",'wb')
writer = csv.writer(writer, delimiter=',')
for row in reader:
if row['Packets_Type'] == 'ICMP_tt':
writer.writerow(row)
By executing those lines of code, I found this error: 通过执行这些代码行,我发现了此错误:
writer.writerow(row)
_csv.Error: sequence expected
I would be very grateful if you could help me please. 如果您能帮助我,我将不胜感激。
If you are open to using pandas
this could be easily done by: 如果您愿意使用pandas
可以通过以下方法轻松完成:
import pandas as pd
reader = pd.read_csv('file.csv')
writer = reader[reader['Packets_Type']=='ICMP_tt']
writer.to_csv('newfile.csv', index=False)
The issue here is that you are importing your data using csv.DictReader
, while at the same time you are exporting the data with csv.writer
. 这里的问题是,您要使用csv.DictReader
导入数据,而同时要使用csv.writer
导出数据。 csv.writer
expects an iterable ( list
or tuple
), but the row values are dictionaries. csv.writer
需要一个可迭代的( list
或tuple
),但行值是字典。 So, the best way to save your data would be to stay consistent and use csv.DictWriter
. 因此,保存数据的最佳方法是保持一致并使用csv.DictWriter
。 The following should work: 以下应该工作:
import csv
with open("file.csv", "rb") as f:
reader = csv.DictReader(f, delimiter=',')
with open("newfile.csv", "wb") as f_out:
writer = csv.DictWriter(f_out, fieldnames=reader.fieldnames, delimiter=",")
writer.writeheader()
for row in reader:
if row['Packets_Type'] == 'ICMP_tt':
writer.writerow(row)
I hope this proves useful. 我希望这证明是有用的。
import pandas as pd
reader = pd.read_csv('file.csv',sep=',')
writer = reader[reader['Packets_Type']=='ICMP_tt']
writer.to_csv('newfile.csv', index=False)import pandas as pd
adding sep=',' should solve the error 添加sep =','应该可以解决错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.