Intermediate · Working with data · topic 31 of 50 · 25 min
CSV files and simple statistics
Explanation
What a CSV file looks like
name,subject,marks
Asha,Maths,82
Ravi,Maths,67
"Sharma, Neha",Maths,91Reading rows with csv.reader
import csv, io
text = "name,marks\nAsha,82\nRavi,67\nMeena,91\n"
reader = csv.reader(io.StringIO(text))
header = next(reader) # the first row
print(header)
for row in reader:
print(row[0], int(row[1]))csv.DictReader: rows as dictionaries
import csv, io
text = "name,marks\nAsha,82\nRavi,67\nMeena,91\n"
total = 0
for row in csv.DictReader(io.StringIO(text)):
print(row)
total += int(row["marks"])
print("Total:", total)Why not just split(",")?
import csv
line = '"Sharma, Neha",Maths,91'
print(line.split(","))
print(next(csv.reader([line])))The statistics module
| Function | In plain words | For 60, 70, 70, 90, 100 |
|---|---|---|
| mean | the average: add all and divide by how many | 78 |
| median | the middle value after sorting | 70 |
| mode | the value that appears most often | 70 |
| stdev | how spread out the values are | about 16.4 |
import statistics as st
marks = [60, 70, 70, 90, 100]
print(st.mean(marks))
print(st.median(marks))
print(st.mode(marks))
print(round(st.stdev(marks), 1))The standard deviation (stdev) is a number for spread. A small stdev means most values sit close to the average, like a class where everyone scored 70 to 80. A large stdev means the values are far apart, like a class with some 30s and some 95s.
Putting it together: monthly expenses
import csv, io, statistics
text = """month,category,amount
Jan,food,4200
Jan,travel,1500
Feb,food,3900
Feb,travel,2100
Mar,food,4500
Mar,travel,1200
"""
food = []
for row in csv.DictReader(io.StringIO(text)):
if row["category"] == "food":
food.append(int(row["amount"]))
print("Food per month:", food)
print("Average:", statistics.mean(food))
print("Median:", statistics.median(food))Watch the lesson
CSV files and simple statistics · 1/6
Most real data comes as tables. In this lesson you will read CSV tables and summarise them with statistics.
Prefer a video by a teacher? Find free videos on “python csv module dictreader statistics mean median” on YouTube ↗
In real life: A class marks report
Teacher Anjali exports her class marks from Google Sheets as CSV. In a few lines Python reads the file, works out the class average and median, and lists the students who scored above the average, ready for the parents meeting.
import csv, io, statistics
data = """name,marks
Asha,82
Ravi,67
Meena,91
Kabir,58
Zoya,74
"""
rows = list(csv.DictReader(io.StringIO(data)))
marks = [int(r["marks"]) for r in rows]
avg = statistics.mean(marks)
print("Average:", round(avg, 1), "| Median:", statistics.median(marks))
print("Above average:", [r["name"] for r in rows if int(r["marks"]) > avg])Practice (0/3 done)
Write column_total(csv_text, column) that reads the CSV text (first line is the header) with csv.DictReader and returns the sum of the given column as an int.
Write mark_stats(csv_text) for CSV text with the columns name,marks. Return a tuple (mean, median) of the marks, with the mean rounded to 1 decimal place. Use the statistics module.
Write above_average(csv_text) for CSV text with the columns name,marks. Return the list of names whose marks are strictly above the mean, in the order they appear.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.