how to extract the min value and max value from csv file using python
Solution 1
You can Use Pandas Where You can load the data into DataFrames and They have inbuilt functions such as Sum,Max,Min,AVG etc.
import pandas as pd
df=pd.read_csv('Name.csv')
#FINDING MAX AND MIN
p=df['ColumnName'].max()
q=df['ColumnName'].min()
print(q)
Thats it You will find the Min value in the Specified column.
Solution 2
This might help
import csv
with open('C:/Users/test/Documents/R_projects/homework/rdu-weather-history.csv', "r") as csvfile:
data = csv.reader(csvfile, delimiter=';')
minVal, maxVal = [], []
for i in data:
minVal.append(i[1])
maxVal.append(i[2])
print min(minVal)
print max(maxVal)
Solution 3
Just in case you want the max and min values in the entire CSV file. This is applicable to even large datasets. Assume that your file is saved as file.csv
import pandas as pd
dff=pd.read_csv('file.csv')
Since you do not want to involve the dates
keep_col= ['temperaturemin','temperaturemax']
I am using your csv but named it file
df=dff[keep_col]
To find specific MAX AND MIN for each column
a=df['temperaturemin'].max()
b=df['temperaturemax'].min()
print(a,"\n",b)
To find MAX AND MIN for the entire file.csv across all columns
print("Min:",df.min().min(),"Max:",df.max().max())
Related videos on Youtube
Ghgh Lhlh
Updated on February 02, 2022Comments
-
Ghgh Lhlh over 2 years
i have a python script that read from csv file and append the requested columns into 2 empty list. after that i need to extract the minimum and maximum value of the columns extracted.
i wrote this code but it seems not working be cause the result is empty .
code:
import csv mydelimeter = csv.excel() mydelimeter.delimiter=";" myfile = open("C:/Users/test/Documents/R_projects/homework/rdu-weather-history.csv") myfile.readline() myreader=csv.reader(myfile,mydelimeter) mywind,mydate=[],[] minTemp, maxTemp = [],[] for row in myreader: print(row[1],row[2]) minTemp.append(row[1]) maxTemp.append(row[2]) print ("min value element : ", min(minTemp)) print ("max value element : ", min(maxTemp))
-
rahularyansharma about 6 yearsstackoverflow.com/questions/21767529/… check this one
-
Rakesh about 6 yearsLooks like you have a typo print ("max value element : ", min(maxTemp)) should be print ("max value element : ", max(maxTemp))
-
DYZ about 6 yearsPossible duplicate of Finding Maximum Value in CSV File
-
-
BruceWayne about 6 yearsYou can also do
q = df["ColumnName"].describe()
which gives you a little more info too. -
Ghgh Lhlh about 6 yearsi tried your answer but it display this error File "C:\Users\test\Documents\Python_Projects\readCSV.py", line 14, in <module> minTemp.append(float(row[1])) builtins.ValueError: could not convert string to float:
-
Rakesh about 6 yearsYou can them remove the float method.