Now read the file from the csv file, do various calculations, and transfer it to another csv file
If you are writing a program and the number of elements in the list has not been determined,
I don't know how to organize the algorithm, so I'm asking you this question.
First, I'm not using the module. The algorithm we put together below is written when there are only four elements in the list.
Therefore, the program does not run when there are less than or equal to four.
infilename = input("Enter the location of your input file : ")
outfilename = input("Enter the location of your output file : ")
infile = open(infilename, "r")
outfile = open(outfilename, "w")
outfile.write("Column,Sum,Mean,STD,Median,Mode,Min,Max\n")
column = 0
for line in infile:
if line:
column += 1
infileline = line.rstrip().split(",")
infileline.sort()
total = float(infileline[0]) + float(infileline[1]) + float(infileline[2]) + float(infileline[3])
mean = total / 4
std = ((float(infileline[0])**2 + float(infileline[1])**2 + float(infileline[2])**2 + float(infileline[3])**2) / 4) - mean**2
median = (float(infileline[1]) + float(infileline[2])) / 2
mode = 2
minimum = float(infileline[0])
maximum = float(infileline[3])
outfile.write(str(column)+',')
outfile.write(','.join("%1.0f"%i for i in (total, mean, std, median,mode, minimum, maximum)))
outfile.write('\n')
infile.close()
outfile.close()
Additionally, just in case, the lowest value (number that appears the most in the list) == mode I would appreciate it if you could also tell me how to define.
python
You can code easily using numpy or counter. Please refer to the code below.
import numpy as np
from collections import Counter
infilename = "in.csv"
outfilename = "out.csv"
infile = open(infilename, "r")
outfile = open(outfilename, "w")
outfile.write("Column,Sum,Mean,STD,Median,Mode,Min,Max\n")
column = 0
for line in infile:
if line:
column += 1
# It changes all the elements of the infileline to float type
infileline = [float(i) for i in line.rstrip().split(",")]
# # sum
total = sum(infileline)
# # average
mean = total / len(infileline)
# # standard deviation
std = sum([i**2 for i in infileline])/len(infileline) - mean**2
# medin: using numpy module
median = np.median(infileline)
# Lowest value: Using the Counter module. Assume that there is only 1 minimum value
most_common = Counter(infileline).most_common()[0][0]
mode = 2
minimum = min(infileline)
maximum = max(infileline)
outfile.write(str(column)+',')
outfile.write(','.join("%1.0f"%i for i in (total, mean, std, median,mode, minimum, maximum)))
outfile.write('\n')
infile.close()
outfile.close()
© 2024 OneMinuteCode. All rights reserved.