Process CSV files in Python - Zero Imports/No Libraries

2024/10/8 13:31:05

I have CSV example like this

ID,TASK1,TASK2,QUIZ1,QUIZ2
11061,50,75,50,78
11062,70,80,60,50
11063,60,75,77,79
11064,52,85,50,80
11065,70,85,50,80

how do i get the Max, Min and Avg on specific Column? i want the output like this, if i want to get Avg on TASK1

output:

Average of TASK1 is 60.4

or

ID,TASK1,TASK2,QUIZ1,QUIZ2
11061,50,75,50,78
11062,70,80,60,50
11063,60,75,77,79
11064,52,85,50,80
11065,70,85,50,80
AVG,60.4, , , ,

so Far my Code like this helped by OlvinRoght

with open('file.csv',"r") as f:next(f)  # skip first linerows = []for line in f:row = []for column in line.split(",")[1:]:  # skip first columnrow.append(int(column))  # convert string to introws.append(row)max_row = ['Max']  min_row = ['Min']for column in zip(*rows):max_row.append(str(max(list(zip(*rows))[0])))min_row.append(str(min(list(zip(*rows))[0])))print(','.join(max_row))print(','.join(min_row))
Answer

We can achieve achieve this my maintaining aggregated metrics as a list.

skip_columns = ["ID"]
num_lines = 0min_stat = [None]
max_stat = [None]
sum_stat = [0]with open("file.csv", "r") as f:for line in f:if num_lines == 0:columns = [col.strip() for col in line.split(",")]number_of_colums = len(columns)min_stat = min_stat * number_of_columsmax_stat = max_stat * number_of_columssum_stat = sum_stat * number_of_columselse:                values = [int(col_value.strip()) for col_value in line.split(",")]for idx, v in enumerate(values):min_stat[idx] = min(v if min_stat[idx] is None else min_stat[idx], v)max_stat[idx] = max(v if max_stat[idx] is None else max_stat[idx], v)sum_stat[idx] += vnum_lines += 1
for idx, col in enumerate(columns):if col in skip_columns:continuestat = stats[col]print(f"Minimum of {col} is {min_stat[idx]}.")print(f"Maximum of {col} is {max_stat[idx]}.")print(f"Average of {col} is {sum_stat[idx] / (num_lines - 1)}.")
https://en.xdnf.cn/q/118697.html

Related Q&A

python - debugging: loop for plotting isnt showing the next plot

I need help in debugging. I just cant figure out why its not working as expected.The Code below should read data files (names are stored in all_files) in chunks of 6, arrange them in subplots (i,j indi…

Return formatted string in Python

I have a string:testString = """ My name is %s and I am %s years old and I live in %s"""I have code that finds these three strings that I want to input into testString. Ho…

How to get the greatest number in a list of numbers using multiprocessing

I have a list of random numbers and I would like to get the greatest number using multiprocessing. This is the code I used to generate the list: import random randomlist = [] for i in range(100000000):…

python pandas yahoo stock data error

i am try to pullout intraday aapl stock data by yahoo. but there problem i facing with my program..import pandas as pd import datetime import urllib2 import matplotlib.pyplot as plt get = http://chart…

Web Scraping Stock Ticker Price from Yahoo Finance using BeautifulSoup

Im trying to scrape Gold stock ticker from Yahoo! Finance. from bs4 import BeautifulSoup import requests, lxmlresponse = requests.get(https://finance.yahoo.com/quote/GC=F?p=GC=F) soup = BeautifulSoup(…

How to convert the radius from meter to pixel?

I have a camera with these specs:full resolution 1280x1024 pixel size 0.0048mm focal length 8 mmI need to detect a ball in this image. It is 4 meters away and its radius is 0.0373 meter. How to convert…

Calculting GPA using While Loop (Python)

A GPA, or Grade point Average, is calculated by summing the grade points earned in a student’s courses and then dividing by the total units. The grade points for an individual course are calculated by…

Return function that modifies the value of the input function

How can I make a function that is given a function as input and returns a function with the value tripled. Here is some pseudo code for what Im looking for. Concrete examples in Python or Scala would b…

how to access the list in different function

I have made a class in which there are 3 functions. def maxvalue def min value def getActionIn the def maxvalue function, I have made a list of actions. I want that list to be accessed in def getaction…

Replacing numpy array with max value [duplicate]

This question already has answers here:numpy max vs amax vs maximum(4 answers)Closed 2 years ago.I have an array, a = np.array([[0,9,8],[5,6,4]])how to replace the each array in axis 1 with the max val…