csv / txt Python中的查找值

时间:2018-06-28 06:28:05

标签: python python-3.x

在我的high_schools.csv文件中,我有这个:

high_school,City,State,zipcode,latitude,longitude
EPISCOPAL,BOISE,ID,83701,43.6,-116

我想查看值是否存在,然后返回邮政编码,纬度和/或经度

到目前为止,这是我要检查的内容,但它正在检查整个行,而不仅仅是开始。

def find_voucher(high_school, city,state,filename):
    with open(filename, 'rU') as f:
        return ("{0},{1},{2}".format(high_school,city,state)) in f

当我运行此命令时,它将返回False,因为它与整行匹配,而不仅仅是前3列。如何更改它以匹配第一部分并返回整行或仅返回邮政编码,纬度,经度?

find_voucher('EPISCOPAL', 'BOISE', 'ID', 'C:/high_schools.csv')    

5 个答案:

答案 0 :(得分:1)

使用environment { VERSION = readMavenPom().getVersion() } 模块。

演示:

csv

输出:

import csv

def find_voucher(high_school, city,state,filename):
    with open(filename, "r") as infile:
        reader = csv.reader(infile)
        next(reader)
        for line in reader:
            if [high_school, city,state] == line[:3]:
                return line[3:] 

print( find_voucher('EPISCOPAL', 'BOISE', 'ID', filename) )

答案 1 :(得分:1)

您需要编写一条if语句,以检查您传入的值:

['83701', '43.6', '-116']

答案 2 :(得分:1)

您可以使用csv.DictReader()将行转换为字典,然后可以通过简单的查询显式检查传入的值。

代码:

from csv import DictReader

def find_voucher(high_school, city, state, filename):
    with open(filename) as csvfile:
        reader = DictReader(csvfile)

        for row in reader:

            # check the arguments against the row
            if (row['high_school'] == high_school and
                row['City'] == city and
                row['State'] == state):

               return dict(row)

输出:

{'high_school': 'EPISCOPAL', 'City': 'BOISE', 'State': 'ID', 'zipcode': '83701', 'latitude': '43.6', 'longitude': '-116'}

Python 3.6 中,DictReader()返回一个collections.OrderedDict(),因此您只需包装dict()即可返回普通字典。如果这不打扰您,您可以将其保留为return row,因为OrderedDict()只是一个有序字典。

答案 3 :(得分:0)

# import pandas as pd
import pandas  

# load 1st row of the csv file into the df
df = pd.read_csv('high_school.csv', nrows = 1)

# lock the slice of the loaded df which matches the condition. the condition is set for the column value being in the list of expected values
df = df.loc[(df['City'].isin(['BOISE']))]

# return the needed columns from sliced dataframe
df = df.iloc[:,[3,4,5]]

答案 4 :(得分:0)

您可以使用pandas模块。

import pandas as pd
df = pd.read_csv(filename)
row = df.query('high_school == "EPISCOPAL" & City=="BOISE" & State=="ID"')

这里是这样的数据帧:

  high_school   City State  zipcode  latitude  longitude
0   EPISCOPAL  BOISE    ID    83701      43.6       -116

您将获得所需的行,并且可以从中返回所需的任何列值。 省去编写所有循环的麻烦。