python CSV,找到最大值并打印信息

时间:2018-10-20 11:33:14

标签: python csv

我的目的是找到单个列的最大值并打印出信息。但是当我打印一些信息时会出现问题。例如CSIT135,什么都没有打印出来。 CSIT121仅打印出一个结果。 我的数据如下:

  

名字,姓氏,学生编号,CSIT110,CSIT121,CSIT135,CSIT142
  Peter,Tan,S1012342D,89,67,54,78
  John,Lim,S1014322H,87,78,86,67
  Ada,Ang,S1023456I,54,78,65,54

def test():
 import csv          
 with open("data.csv") as a:     
     rows = csv.DictReader(a)      
     t2_list=[]
     for row in rows: 
         t2 = row['CSIT121']
         t2_list.append(t2)
         CSIT121=max(t2_list)           
     if row['CSIT121']==CSIT121:
         print("{0:<8}| {1:>10} | {2:<8}".format("CSIT121", "John","Lim"))
         print("{0:<8}| {1:>10} | {2:<8}".format("CSIT121", row['first_name'],row['last_name']))


 with open("data.csv") as a:     
     rows = csv.DictReader(a)      
     t3_list=[]
     for row in rows: 
         t3 = row['CSIT135']
         t3_list.append(t3)
         CSIT135=max(t3_list)  
         if row['CSIT135']==CSIT135:
             print("{0:<8}| {1:>10} | {2:<8}".format("CSIT135", row['first_name'],row['last_name'])) 

Code sample and run result pic

2 个答案:

答案 0 :(得分:0)

您是否正在考虑为每一列复制代码并一次又一次地读取文件? Chose DRY instead of WET

第一步应该是将文件转换为便于解决问题的文件。我决定去字典(键是列),值是列中值的列表。

import csv
datas = {}
with open("data.csv") as f:   
    csvreader = csv.DictReader(f) 
    for row in csvreader:
        for key in 'CSIT110', 'CSIT121', 'CSIT135', 'CSIT142':
            datas.setdefault(key, []).append(int(row[key]))

现在我需要处理一些事情,我遍历字典并使用max()函数。

for key, value in datas.items():
    max_value = max(value)
    print('key : {}, max : {}'.format(key, max_value))

您可以使用pandas来解决此问题。

import pandas as pd
df = pd.read_csv('data.csv')
for key in 'CSIT110', 'CSIT121', 'CSIT135', 'CSIT142':
    print('key : {}, max : {}'.format(key, df[key].max()))

两个代码的结果:

key : CSIT110, max : 89
key : CSIT121, max : 78
key : CSIT135, max : 86
key : CSIT142, max : 78

您需要有关包含最大值的行的所有信息吗? :

import pandas as pd
df = pd.read_csv('data.csv')
for key in 'CSIT110', 'CSIT121', 'CSIT135', 'CSIT142':
    row = df.loc[df[key].idxmax()]
    print('Max of {} : '.format(key))
    print(row)

结果:

Max of CSIT110 : 
first_name        Peter
last_name           Tan
student_id    S1012342D
CSIT110              89
CSIT121              67
CSIT135              54
CSIT142              78
Name: 0, dtype: object
Max of CSIT121 : 
first_name         John
last_name           Lim
student_id    S1014322H
CSIT110              87
CSIT121              78
CSIT135              86
CSIT142              67
Name: 1, dtype: object
Max of CSIT135 : 
first_name         John
last_name           Lim
student_id    S1014322H
CSIT110              87
CSIT121              78
CSIT135              86
CSIT142              67
Name: 1, dtype: object
Max of CSIT142 : 
first_name        Peter
last_name           Tan
student_id    S1012342D
CSIT110              89
CSIT121              67
CSIT135              54
CSIT142              78

答案 1 :(得分:0)

您尚未指定输出的格式,因此,我没有打印结果,而是编写了函数,该函数返回dict,其中每个键代表每一列,每个包含dict的值代表该行中具有最大值的行。

我不喜欢文件倒带部分,但是这似乎是必要的,因为在迭代过程中,csv.DictReader使用的是构造函数中接收到的文件句柄,并且在迭代之后不倒带它。 这可能就是为什么您的代码只看到一个结果的原因。

instance Monoid a => Monoid (Optional a) where
    mempty = Nada
    mappend x Nada = x
    mappend Nada x = x
    mappend (Only x) (Only y) = Only (Prelude.mappend x y)

输出:

import csv

def get_maxes():
    with open("data.csv", "r") as data_file:
        data = csv.DictReader(data_file)

        # don't process first 3 colums
        columns_to_process = data.fieldnames[3:]
        column_max = {}
        for column in columns_to_process:
            data_file.seek(0) # rewind the file after iteration in line above
            data_file.readline() # skip the first line with header

            column_max[column] = max(data, key=lambda x: x[column])

    return column_max

if __name__ == '__main__':
    print(get_maxes())

编辑:

如果您一次使用DictReader中的所有行,则无需倒回文件:

{'CSIT110': {'CSIT110': '89',
             'CSIT121': '67',
             'CSIT135': '54',
             'CSIT142': '78',
             'first_name': 'Peter',
             'last_name': 'Tan',
             'student_id': 'S1012342D'},
 'CSIT121': {'CSIT110': '87',
             'CSIT121': '78',
             'CSIT135': '86',
             'CSIT142': '67',
             'first_name': 'John',
             'last_name': 'Lim',
             'student_id': 'S1014322H'},
 'CSIT135': {'CSIT110': '87',
             'CSIT121': '78',
             'CSIT135': '86',
             'CSIT142': '67',
             'first_name': 'John',
             'last_name': 'Lim',
             'student_id': 'S1014322H'},
 'CSIT142': {'CSIT110': '89',
             'CSIT121': '67',
             'CSIT135': '54',
             'CSIT142': '78',
             'first_name': 'Peter',
             'last_name': 'Tan',
             'student_id': 'S1012342D'}}
相关问题