如何用python在CSV文件中查找数据

2024-10-01 09:33:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个问题,我想用python从csv文件中搜索数据

我的代码是这样的

#search process area
area_proses = []
sg1 = []
sg2 = []
sg3 = []
avg = []

#input number you want to search
number = raw_input('Masukan id Spesific Goal\n')

#read csv, and split on "," the line
csv_file = csv.reader(open('C:/xampp_2/htdocs/SkripsiV2/fuzzy/download.csv', "rb"), delimiter=",")

#loop through csv list
for row in csv_file:
    area_proses.append(row[1])
    sg1.append(row[2])
    sg2.append(row[3])
    sg3.append(row[4])
    avg.append(row[5])
    #if current rows 1nd value is equal to input, print that row
    if number == row[0]:
        #masukan data
         print(area_proses,sg1,sg2,sg3,avg)

我的问题是,当我用id 11搜索时,输出如下所示:

^{pr2}$

但当我搜索id 12时,输出如下:

 (['area_proses', 'Service Delivery', 'Incident Resolution and Prevention'], ['sg
    1', '3.71', '3.83'], ['sg2', '3.48', '3.65'], ['sg3', '3.30', '3.70'], ['avg', '
    3.50', '3.73'])

我怎样才能解决这个问题?在

在下载.csv在

"id","area_proses","sg1","sg2","sg3","avg","fuzzy",
"11","Service Delivery","3.71","3.48","3.30","3.50","0.00000000000",
"12","Incident Resolution and Prevention","3.83","3.65","3.70","3.73","0.00000000000",
"13","Service System Development","3.93","3.29","3.26","3.49","0.00000000000",
"14","Service System Transition","3.00","3.43","0.00","3.22","0.00000000000",
"15","Strategic Service Management","3.48","3.86","0.00","3.67","0.00000000000",
"16","Configuration Management","3.14","3.57","0.00","3.36","0.00000000000",
"17","Measurement and Analysis","2.93","3.18","0.00","3.06","0.00000000000",

Tags: andcsvidnumberinputsearchservicearea
2条回答

把“rb”改成“r”

fopn = open(file_loc, "r")
   csv_file = csv.reader(fopn)
   for row in csv_file:
       if number == row[0]:
          print(row)

尝试使用熊猫图书馆。安装它,然后执行以下操作:

import pandas as pd
df = pd.read_csv('csv_file.csv')

df[df['id'] == number]

相关问题 更多 >