从csv文件获取数据

时间:2018-09-27 19:45:38

标签: python python-3.x

import CSV 
with open("statefinancials.csv") as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
        for row in csv_reader:
            if line_count == 0:
                print(f'Column names are {", ".join(row)}')
                line_count += 1
            else:
                print(" rating >=3.00")

我有一个包含数据的Excel文件

     State    Year to date sales       Company Name       Rating
      GA           234333                  xx               2.35
      NV           234333                  xx               4.02
      TX           311122                  kl               3.93
      "            "                         "               "
      etc......

我需要获取> 3.0评级的数据。我的代码在某个地方出错。

2 个答案:

答案 0 :(得分:1)

尝试使用pandas

import pandas as pd
csv_reader = pd.read_csv('statefinancials.csv', delimiter=',')
csv_reader['Rating'] = csv_reader['Rating'].astype(float) # or float64
line_count =  len(csv_reader[csv_reader['Rating']>3.0])
print ("Rows with Rating greater than 3 = ",line_count)

答案 1 :(得分:0)

import csv
with open('statefinancials.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    column_names = next(csv_reader)
    index_of_rating = column_names.index('Rating')
    for row in csv_reader:
        # get rating value by using index of rating and compare with 3
        if float(row[index_of_rating]) > 3:
            print('Rating is greater than 3')

您可以通过使用内置功能的索引功能找到收视率的索引。之后,您需要迭代到每一行来比较每行中的评分值。