[英]Selecting specific rows of csv based on a column's value in python
我有一个 csv 文件,我正在使用 DictReader 读取它,我想根据 Name 列中的值是否与我作为列表给出的名称匹配来选择文件的行。
该文件如下所示:
Name Age Gender
Matt 22 M
Jen 21 F
Greg 22 M
我试过这样的事情,但行返回为空
file = csv.DictReader("file.csv',fieldnames=fieldnames,delimiter='~')
Names = ['Greg', Jen']
for i in Names:
rows = [row for row in file if row['Name'] == i]
我希望代码生成以下行: {Jen: 21: F, Greg: 22: M}
我不确定这种格式是否正确。
请注意,由于我无法控制的限制,我故意不使用诸如熊猫之类的数据框库。
"file.csv'
引号不"file.csv"
:它应该是"file.csv"
或'file.csv'
。 Names = ['Greg', Jen']
缺少引号;它应该是Names = ['Greg', 'Jen']
. 分隔符应该是' '
(一个空格)。你需要在调用Dictreader
方法之前打开文件。最后:for 循环可以简化。
工作代码示例:
import csv
with open('example.csv', newline='') as csvfile:
file = csv.DictReader(csvfile, delimiter=' ')
Names = ['Greg', 'Jen']
print(file)
rows = [row for row in file if row['Name'] in Names]
在 example.csv 文件中:
Name Age Gender
Matt 22 M
Jen 21 F
Greg 22 M
您在循环中使用了运算符==
。 取下环和使用操作in
rows = [row for row in file if row['Name'] in Names]
迭代行一次比迭代每个名称的行更有效。 对于大文件尤其如此。
filtered_rows = []
for row in file:
if row['Name'] in Names:
filtered_rows.append(row)
使用列表理解的相同解决方案
filtered_rows = [
row
for row in file
if row['Name'] in Names
]
您读取 csv 文件的方式不正确csv.DictReader 示例。 此代码应该工作:
Names = ["Greg", "Jen"]
with open("csvFile.csv", newline='') as csvfile:
reader = csv.DictReader(csvfile)
rows = [row for row in reader if row['Name'] in Names]
print(rows)
输出是:
[{'Gender': 'F', 'Name': 'Jen', 'Age': '21'}, {'Gender': ' M', 'Name': 'Greg', 'Age': '22'}]
您没有正确打开文件。 将分隔符和您的代码更改为:
from csv import DictReader
with open('test.csv', mode='r') as csv_file:
file = DictReader(csv_file,delimiter=';')
Names = ['Greg', 'Jen']
rows = [row for row in file if row['Name'] in Names]
print(rows)
我得到的输出是:
[{'Gender': 'M', 'Name ': 'Greg ', 'Age ': '22'},{'Gender': 'F', 'Name ': 'Jen ', 'Age ': '21'}]
如果您想了解有关使用 python 的 csv 的更多信息,请查看此链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.