Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

ESP task 4a (4 of 5): Data from CSV files and charts

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

45 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

Which hour is the busiest?

The manager asks: "Which hour is the busiest? Who books the most?"

The club has 300 bookings in a file. Counting by hand takes hours. A short program does it in a second.

In the project you may be given a data file and asked questions like these.

Key words

WordWhat it meansExample
CSVA text file where each line is a record and commas separate the fields.Sam,1,10
DatasetA collection of data about one subject.all the bookings
Data frameA table of data inside pandas, with rows and columns.one row per booking
LibraryCode somebody else wrote that you can use.pandas
TrendA pattern that goes up or down over time.more bookings each week
AverageThe total divided by how many values there are.(12 + 8 + 10) divided by 3 is 10
AxisA line of a chart with a scale and a label.hour along the bottom
LegendA small box that says what each colour or line means.blue is Court 1

The cells students fill in are left blank in this preview.

Try it: count with plain Python

Code: python
text = "member,court,hour\nSam,1,10\nSam,2,11\nAisha,1,10\nLee,2,10\n"

lines = text.strip().split("\n")
counts = {}
for i in range(1, len(lines)):    # start at 1 to skip the header
    hour = lines[i].split(",")[2]
    if hour in counts:
        counts[hour] = counts[hour] + 1
    else:
        counts[hour] = 1

print(counts)

# Hour 10 has 3 bookings.
# Add another line to the text and run it again.

Make a free account to save your work and track your progress.

Worked example: an average

StepWhat you doResult
1Bookings on Monday, Tuesday and Wednesday12, 8 and 10
2Add them up12 + 8 + 10 = 30
3Count how many days3
4Divide the total by the count30 divided by 3 = 10
5Say it in wordsThe club has 10 bookings a day on average

The cells students fill in are left blank in this preview.

pandas does the same job in fewer lines

Code: python
import pandas as pd

# bookings.csv has the columns: member, court, hour, price, week
data = pd.read_csv("bookings.csv")

print(data["hour"].value_counts())    # count each hour
print(data.groupby("member").size())  # bookings per member
court_one = data[data["court"] == 1]  # keep only the rows for court 1
print(len(court_one))                 # bookings on court 1
print(data["price"].sum())            # the total money
print(data["price"].mean())           # the average price

# A trend over time: bookings in each week, in week order.
print(data.groupby("week").size())    # a rise or fall from week to week is a trend

Make a free account to save your work and track your progress.

Where pandas runs

Note

The pandas and matplotlib blocks are for reading. The lesson window has only plain Python. Run them in the Python set-up your lecturer gives you. The tasks in this lesson use plain Python so they run anywhere.

Match the question to the chart

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

A chart with matplotlib: bars and a legend

Code: python
import matplotlib.pyplot as plt

court_one = [4, 9, 6, 3]   # bookings at 9, 10, 11 and 12
court_two = [2, 5, 4, 1]

left = [8.8, 9.8, 10.8, 11.8]   # Court 1 bars a little left of each hour
right = [9.2, 10.2, 11.2, 12.2] # Court 2 bars a little right
plt.bar(left, court_one, width=0.4, label="Court 1")
plt.bar(right, court_two, width=0.4, label="Court 2")
plt.title("Bookings in each hour")
plt.xlabel("Hour of the day")
plt.ylabel("Number of bookings")
plt.legend()
plt.show()

Make a free account to save your work and track your progress.

Five parts of a good chart

PartWhy
A titleSays what the chart is about
Labels on both axesSays what the numbers mean, with units
The right kind of chartBars to compare, lines for change over time
A legend if there is more than one line or colourSays what each one means
Clear coloursAnyone can read it, including people who cannot tell some colours apart

The cells students fill in are left blank in this preview.

Check: charts and data

Have a go

Check: charts and data

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Stage 4a: answer the manager

This is stage 4a of the Hillside practice project. Answer the manager's two questions with plain Python. The data is CSV text with a header line: member,court,hour. bookings_per_member gives a dictionary of names and counts. busiest_hour gives the hour with the most bookings; if two are equal, give the earlier hour. Press Run Tests to check your work.

Code: python
def bookings_per_member(text):
    # text is CSV text. The first line is the header: member,court,hour
    # Give back a dictionary: each member's name and how many bookings they have.
    # Give back {} if there are no bookings.
    return None


def busiest_hour(text):
    # Give back the hour with the most bookings.
    # If two hours have the same number, give back the earlier hour.
    # Give back None if there are no bookings.
    return 0

Make a free account to save your work, or press Start lab to work through the whole lesson.

Stage 4a: plan a chart

The manager wants to see how many bookings there are in each hour, 9 to 20. Plan the chart. Say which type of chart you choose and why. Write the title, the label for each axis and what the numbers mean. Draw a quick sketch or a table of the data. Then write two sentences for the manager, in plain words, saying what the chart shows.

A teacher marks this in a college. Nothing you write here is kept: it goes when you leave the page.

Make a free account to save your work, or press Start lab to work through the whole lesson.

Key words crossword

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Final check

Have a go

Final check

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.