python CSV , find max and print the information

2024/9/22 5:42:57

My aim is to find the max of the individual column and print out the information. But there is problem when I print some of the information. For example CSIT135, nothing was printed out. CSIT121 only prints out one result. My data looks like:

first_name,last_name,student_id,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

Answer

You haven't specified the format of the output, so instead of printing the result I written function returning dict with each key representing each column and each value containing dict representing row with max value in that column.

I don't like the file rewinding part, but it seems to be necessary, because the csv.DictReader during iteration is using the file handle it has received in the constructor and doesn't rewind it after the iteration. This might be why you only see one result with your code.

import csvdef get_maxes():with open("data.csv", "r") as data_file:data = csv.DictReader(data_file)# don't process first 3 columscolumns_to_process = data.fieldnames[3:]column_max = {}for column in columns_to_process:data_file.seek(0) # rewind the file after iteration in line abovedata_file.readline() # skip the first line with headercolumn_max[column] = max(data, key=lambda x: x[column])return column_maxif __name__ == '__main__':print(get_maxes())

Output:

{'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'}}

EDIT:

If you consume all the rows at once from the DictReader you don't need to rewind the file:

import csvdef get_maxes():with open("data.csv", 'r') as data_file:data = csv.DictReader(data_file)columns_to_process = data.fieldnames[3:] # don't process first 3 columsdata = [row for row in data] # read all the data from DictReader and store it in the listcolumn_max = {}for column in columns_to_process:column_max[column] = max(data, key=lambda x: x[column])return column_maxif __name__ == '__main__':import pprintpprint.pprint(get_maxes())
https://en.xdnf.cn/q/119622.html

Related Q&A

Error on python3 on windows subsystem for linux for fenics program

Im just starting to use fenics in python3 on windows subsystem ubuntu, and when I open the first titurial file I got this error. Solving linear variational problem. Traceback (most recent call last): …

python regex: how to remove hex dec characters from string [duplicate]

This question already has answers here:What does a leading `\x` mean in a Python string `\xaa`(2 answers)Closed 8 years ago.text="\xe2\x80\x94" print re.sub(r(\\(?<=\\)x[a-z0-9]{2})+,&quo…

Iterating through list and getting even and odd numbers

yet one more exercise that I seem to have a problem with. Id say Ive got it right, but Python knows better. The body of the task is:Write a function that takes a list or tuple of numbers. Return a two-…

Cannot import tensorflow-gpu

I have tried to import tensorflow-gpu and Im getting the same error with different versions of CUDA and cuDNN. My GPU is compatible with CUDA and I have no problems installing but when I try to import …

comparing two Dataframe columns to check if they have same value in python

I have two dataframes,new1.Name city0 sri won chn1 pechi won pune2 Ram won mum0 pec won keralanew3req 0 pec 1 mutI tried, mask=new1.Name.str.contains("|".join(…

Input gravity forms entries in a database locally stores (created with python)

I hope you are all doing alright. Is it possible to connect a gform entry to a database created with Python and stored in my PC with a little variation of the following code? add_action("gform_af…

Cant get javascript generated html using python

Im trying to create a python script that automatically gets the content of a table on a webpage. I manage to have it to work on pure html page, but there is one website that gives me headache... The ht…

Python: Extract text from Word files in a url

Given the url containing a certain file, in this case a word document, read the contents of the document. I have seen several examples of how to extract text from local documents but not from a url. Wo…

Python3:Plot f(x,y), preferably using matplotlib

Is there a way, preferably using matplotlib, to plot a 2-variable function f(x,y) in python; Thank you, in advance.

Why does my cronjob not send the email from my script? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…