Python for data, from zero

Install Python, learn the basics one small step at a time, then load, clean, summarise and chart a table with pandas and matplotlib. No experience needed.

Every box with a Run button is real Python. Change the code and press Run to try it in your browser. The first Run loads Python into the page (about 20 MB, once). The output under each box is what the code prints when you run it on a computer, so you can read the whole page without running anything.

1. Get set up

What Python is, the tools around it, and how to run your first line. If you cannot install anything, skip to 1.7 and use a free online notebook.

  1. 1.1 What Python is
  2. 1.2 The terminal
  3. 1.3 Install Python
  4. 1.4 Virtual environments
  5. 1.5 Install libraries with pip
  6. 1.6 Write and run a .py file in VS Code
  7. 1.7 Notebooks, and Python with nothing installed

1.1 What Python is

Python is a programming language. A programming language is a way to write instructions for a computer in words and symbols that people can read too. You type the instructions, and Python carries them out one line at a time, top to bottom.

People who work with data use Python because it is free, it reads a lot like English, and it has ready-made tools for the jobs they do every day: loading a table, cleaning it, summing it up and drawing a chart. These ready-made tools are called libraries. This page uses two: pandas for tables and matplotlib for charts.

Here is a whole Python program. It is one line long. print means “show this on the screen”, and the text inside the quote marks is what gets shown. Press Run to try it.

Example
Output
Hello

You will see Hello. That is all a program is: instructions, and what they produce.

1.2 The terminal

The terminal is a window where you type commands to your computer instead of clicking. You type a command, press Enter, and the computer prints a reply. You will use it to install things and to run your Python files.

On a Mac: press Cmd + Space, type Terminal and press Enter. On Windows: press the Windows key, type PowerShell and press Enter.

The terminal is always “in” one folder at a time. A folder (also called a directory) is the same thing you see in Finder or File Explorer. These three commands work on both Mac and Windows:

Terminal
pwd                    # print the folder you are in now
mkdir data-practice    # make a new folder called data-practice
cd data-practice       # move into that folder

The # and the words after it are notes for you. Do not type them. cd stands for “change directory”. cd .. goes back up one folder.

1.3 Install Python

Go to python.org/downloads, download the newest version for your computer and run the installer.

On Windows, tick the box that says Add python.exe to PATH on the first screen of the installer. PATH is the list of places your computer looks for programs. If you skip this box, the terminal will not find Python.

Then close the terminal, open a new one, and check it worked:

Mac
python3 --version
Windows
python --version

It prints one line with the version, such as Python 3.13.1. Your numbers may be different. Anything from 3.10 up is fine. On a Mac you type python3; on Windows you type python (or py).

1.4 Virtual environments

A virtual environment is a private box of Python tools for one project. Libraries you install go into that box, not into your whole computer. So one project cannot break another, and if something goes wrong you can delete the box and start again.

Make one inside your data-practice folder. -m venv means “run Python's built-in venv tool”. .venv is the name of the folder it makes. The dot at the start hides the folder in Finder.

Mac
cd data-practice
python3 -m venv .venv
source .venv/bin/activate
Windows
cd data-practice
python -m venv .venv
.venv\Scripts\activate

The last line activates it: it tells this terminal to use the box. You will see (.venv) at the start of the line. Once it is active, python means the Python inside the box, on Mac and Windows alike.

You need to activate it again each time you open a new terminal. Type deactivate to leave it.

If Windows says “running scripts is disabled on this system”, run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned once, answer Y, and try again.

1.5 Install libraries with pip

pip is the tool that downloads and installs libraries. It comes with Python. With your virtual environment active, install pandas and matplotlib:

Terminal
pip install pandas matplotlib

pip prints a lot of lines as it works and ends with Successfully installed .... To check pandas is there, ask Python to load it and print its version:

Terminal
python -c "import pandas; print(pandas.__version__)"

It prints a version number, such as 2.3.3. If it says ModuleNotFoundError, your virtual environment is probably not active. See the mistakes below.

1.6 Write and run a .py file in VS Code

A Python program usually lives in a file whose name ends in .py. The ending tells the computer it holds Python. You can write it in any text editor. VS Code is a free one that most people use.

1. Download it from code.visualstudio.com and open it.
2. Choose File > Open Folder and pick data-practice.
3. Click the Extensions icon on the left (four squares), search Python and install the one by Microsoft.
4. Press Cmd/Ctrl + Shift + P, type Python: Select Interpreter and pick the one with .venv in it. The interpreter is the program that reads and runs your Python.
5. Make a new file called hello.py, type the code below and save it.

Example hello.py
Output
Hello from a file, world

6. Open the terminal inside VS Code (Terminal > New Terminal) and type python hello.py. The output above appears. You can also press the small ▶ button at the top right of the file.

1.7 Notebooks, and Python with nothing installed

A notebook is a document that mixes small boxes of code (called cells) with their output and your notes. You run one cell at a time and see the result straight underneath. That makes it handy for exploring data. Jupyter is the classic one: pip install jupyterlab, then jupyter lab opens it in your browser.

If you cannot install anything (a school laptop, say), use a free online notebook. Google Colab runs in your browser with a Google account and already has pandas and matplotlib. To use the practice file there, click the folder icon on the left and upload offers.csv.

The same Python on this page runs in notebook tools like Jupyter, Google Colab and Hex, in a .py file, and in the Run boxes here. Only the place you type it changes.

Common mistakes

  • Typing Python code straight into the terminal's command line. Code goes in a .py file (or a notebook cell). The terminal is for commands like python hello.py.
  • Forgetting to activate the virtual environment, then getting ModuleNotFoundError: No module named 'pandas'. Look for (.venv) at the start of the line.
  • On Windows, not ticking Add python.exe to PATH. Run the installer again and choose Modify, or reinstall with the box ticked.
  • Saving the file as hello.py.txt by accident. Check the full file name in VS Code's file list.
  • Running python hello.py from the wrong folder. Use pwd to see where you are and cd to move.

Try it

Exercise 1. Make a folder called data-practice, make a virtual environment in it, and activate it.

Hint

Three steps: mkdir, cd, then -m venv and activate. 1.2 and 1.4 have every command.

Show answer
# Mac
mkdir data-practice
cd data-practice
python3 -m venv .venv
source .venv/bin/activate

# Windows
mkdir data-practice
cd data-practice
python -m venv .venv
.venv\Scripts\activate

You know it worked when (.venv) shows at the start of the line.

Exercise 2. With the environment active, install pandas and matplotlib and check that pandas loads.

Hint

One pip install line, then the python -c check from 1.5.

Show answer
pip install pandas matplotlib
python -c "import pandas; print(pandas.__version__)"

A version number means pandas is installed in this environment.

Exercise 3. Write a file called me.py that prints your first name and the city you live in, on two lines. Run it.

Hint

Two print lines. Text goes inside quote marks.

Show answer
Answer
Output
Aoife
Galway

Each print starts a new line. Run it with python me.py.

2. Python basics

The small set of ideas you need before pandas makes sense. Each one builds on the last. Take them in order.

  1. 2.1 Values, variables and print
  2. 2.2 Numbers and maths
  3. 2.3 Text (strings)
  4. 2.4 True, False and comparisons
  5. 2.5 Lists
  6. 2.6 Dictionaries
  7. 2.7 Making decisions: if, elif, else
  8. 2.8 Repeating things: for loops
  9. 2.9 Functions: your own reusable steps
  10. 2.10 Importing a library
  11. 2.11 Reading an error message

2.1 Values, variables and print

A value is a piece of data, like the number 12 or the text "Dublin". A variable is a name that holds a value, so you can use it later.

The = sign means “store the value on the right under the name on the left”. It is not “equals” as in maths. print() shows values on the screen. You can give it several things, split by commas, and it puts a space between them.

Example
Output
Dublin
12
Offers in Dublin = 12
15

The last two lines show something new people find odd. offers = offers + 3 works out the right side first (12 + 3), then stores 15 back under the same name.

Common mistakes

  • Names are case-sensitive. City and city are two different names. Using one you never made gives NameError.
  • Names cannot have spaces or start with a number. Use underscores: base_salary, not base salary.
  • Using a variable on a line above the one that creates it. Python reads top to bottom.

Try it

Exercise 1. Make a variable called company that holds the text Fernway, and print it.

Hint

Text needs quote marks around it. Then print(company), with no quote marks, to print what the name holds.

Show answer
Answer
Output
Fernway

print("company") with quote marks would print the word company, not the value.

Exercise 2. Make salary equal to 50000. On the next line, increase it by 2000. Print it.

Hint

Same pattern as offers = offers + 3.

Show answer
Answer
Output
52000

You can also write salary += 2000, which is short for the same thing.

2.2 Numbers and maths

Python has two main kinds of number. An int (integer) is a whole number, like 52000. A float is a number with a decimal point, like 0.1. Maths works as you would expect, with * for times and / for divide.

Example
Output
5200.0
56000
4333.333333333333
4333.33
3 1
8

round() is a function: a named action you call by writing its name and brackets. What goes in the brackets are its inputs. Here: the number, and how many decimal places.

Common mistakes

  • Writing 52,000 with a comma. Python reads the comma as a separator and makes two numbers. Write 52000, or 52_000 if you want it easier to read.
  • Writing 10% as 10. In maths it is 0.10.
  • Being surprised that 0.1 + 0.2 prints 0.30000000000000004. Computers store decimals slightly off. Use round() when you show results.

Try it

Exercise 1. A yearly salary is 60000. Work out the monthly amount, rounded to 2 decimal places.

Hint

Divide by 12, then wrap it in round(..., 2).

Show answer
Answer
Output
5000.0

60000 divides evenly, so you see 5000.0: the .0 is there because / always gives a float.

Exercise 2. A salary went from 50000 to 54000. What is the percentage rise?

Hint

Change divided by the old value, times 100.

Show answer
Answer
Output
8.0

Brackets go first, as in maths. This exact sum comes back in pandas as pct_change.

2.3 Text (strings)

Text in Python is called a string, short for “a string of characters”. You put it in quote marks, single or double. Strings come with built-in actions called methods, which you call with a dot: text.upper().

Example
Output
Data Science
12
DATA SCIENCE
Cork
Data Science pays 61,500 a year

The last line is an f-string. Put f before the opening quote and any variable inside { } is filled in. :, adds commas to big numbers. It is the easiest way to mix text and numbers.

Common mistakes

  • Joining text and a number with +: "Pay: " + 61500 gives TypeError. Use an f-string.
  • Forgetting the f, so {salary} is printed as it is.
  • Thinking .strip() changes the original. It gives back a new string. Store it: city = city.strip().

Try it

Exercise 1. Clean city = " galway " so it prints as Galway.

Hint

Two methods, one after the other: one removes the spaces, one capitalises.

Show answer
Answer
Output
Galway

You will do exactly this to whole columns in pandas, with .str.strip().

Exercise 2. With company = "Bluebell" and salary = 58000, print Bluebell offered 58,000.

Hint

An f-string, with :, for the comma.

Show answer
Answer
Output
Bluebell offered 58,000

The f-string fills in both values and formats the number.

2.4 True, False and comparisons

A comparison asks a yes-or-no question and gives back True or False. These two values are called booleans. They matter because filtering data is just asking a yes-or-no question about every row.

Example
Output
True
False
True
True
True
False

Common mistakes

  • Using = when you mean ==. One = stores a value. Two asks a question.
  • Writing true. It must be True with a capital T.
  • Comparing text with a number: "58000" == 58000 is False, because one is a string and one is an int.

Try it

Exercise 1. Is 47000 at least 45000? Print the answer.

Hint

“At least” is >=.

Show answer
Answer
Output
True

>= is greater than or equal to. <= is less than or equal to.

Exercise 2. With level = "Senior" and city = "Cork", print whether the offer is Senior and in Dublin.

Hint

Two == questions joined with and.

Show answer
Answer
Output
False

The first part is True and the second is False, so and gives False.

2.5 Lists

A list holds several values in order, inside square brackets, split by commas. Each item has a position called its index. Counting starts at 0, not 1.

Example
Output
Dublin
Galway
3
['Dublin', 'Cork', 'Galway', 'Berlin']
['Cork', 'Galway']
161000 48000 61000
53666.666666666664
[48000, 52000, 61000]

Common mistakes

  • Asking for cities[3] in a three-item list gives IndexError: list index out of range. The last index is always one less than the length.
  • Forgetting the commas between items.
  • Expecting cities.append("Berlin") to give back the new list. It changes the list in place and gives back nothing.

Try it

Exercise 1. What is the average of [55000, 47000, 62000, 58000]?

Hint

sum() divided by len().

Show answer
Answer
Output
55500.0

This is the mean. Python's statistics library also has mean and median, which you will meet in 2.10.

Exercise 2. Make a list of the companies Northwind, Bluebell and Fernway. Add Larkspur to the end. Print the second company and then the whole list.

Hint

The second item is at index 1.

Show answer
Answer
Output
Bluebell
['Northwind', 'Bluebell', 'Fernway', 'Larkspur']

Index 1 is the second item because counting starts at 0.

2.6 Dictionaries

A dictionary (or dict) stores values under names. Each name is a key, and each key has a value. You write them inside curly brackets as key: value. You look things up by key, like a word in a real dictionary.

One row of a table is a lot like a dict: column names are the keys, and that row's data are the values. Data from websites (JSON, in part 3) looks like this too.

Example
Output
Fernway
{'company': 'Fernway', 'level': 'Senior', 'base_salary': 74000, 'city': 'Dublin'}
['company', 'level', 'base_salary', 'city']
0

Common mistakes

  • Asking for a key that is not there: offer["bonus"] gives KeyError: 'bonus'. Use .get() if it might be missing.
  • Keys are case-sensitive: "Company" is not "company".
  • Mixing up the brackets. Lists use [ ]. Dicts are made with { } but you still look up with [ ].

Try it

Exercise 1. Make a dict for a Data Analyst offer in Cork at 49000. Print just the salary.

Hint

Three keys, for example job_family, city and base_salary.

Show answer
Answer
Output
49000

Any key names work, as long as you look up the same name you used.

Exercise 2. Here is a list of two dicts. Print the company of the second one.

Starting code
Output
(nothing printed)
Hint

First pick the item from the list with [1], then the key with ["company"].

Show answer
Answer
Output
Quillstone

A list of dicts is the most common shape for raw data. Read it left to right: item 1, then its company.

2.7 Making decisions: if, elif, else

if runs some lines only when a question is True. elif (else if) asks another question if the first was False. else catches everything left.

Two rules that catch everyone at first. The question line ends with a colon :. The lines that belong to it are indented: pushed in by 4 spaces. Indenting is how Python knows which lines are inside the if.

Example
Output
Middle band
Done

Common mistakes

  • Forgetting the colon gives SyntaxError.
  • Uneven indenting gives IndentationError. Use 4 spaces every time. VS Code does this for you when you press Tab.
  • Putting the biggest test last. Python stops at the first True, so check >= 60000 before >= 50000.

Try it

Exercise 1. With level = "Senior", print Needs sign-off if the level is Senior and Standard if not.

Hint

One if and one else. Remember == and the colons.

Show answer
Answer
Output
Needs sign-off

Change the level to "Mid" and run it again to see the other branch.

Exercise 2. An offer took days = 12 days to be accepted. Print Quick if under 7 days, Normal if 7 to 14, and Slow if more.

Hint

if for under 7, elif for up to 14, else for the rest.

Show answer
Answer
Output
Normal

Once days < 7 is False, Python only reaches elif, so it does not need to check days >= 7 again.

2.8 Repeating things: for loops

A for loop runs the same lines once for each item in a list. for s in salaries: means “take each item in turn and call it s”. As with if, the line ends with a colon and the repeated lines are indented.

Example
Output
52000 -> 53560.0
61000 -> 62830.0
48000 -> 49440.0
75000 -> 77250.0
Total: 236000
Round 0
Round 1
Round 2

Pandas does most of this looping for you, on whole columns at once. But you need to know what a loop is to read other people's code and to understand what pandas is doing.

Common mistakes

  • Indenting the final print by mistake, so it prints inside the loop on every round.
  • Forgetting to set total = 0 before the loop.
  • Adding to or removing from the list you are looping over. Build a new list instead.

Try it

Exercise 1. Count how many salaries in [52000, 61000, 48000, 75000, 58000] are above 55000.

Hint

Start a counter at 0. In the loop, use if, and add 1 when it is True.

Show answer
Answer
Output
3

An if inside a loop is indented twice: once for the loop and once for the if.

Exercise 2. Make a new list with each salary raised by 5%, rounded to a whole number.

Hint

Start with an empty list [], then .append() inside the loop.

Show answer
Answer
Output
[54600, 64050, 50400]

round() with no second input rounds to a whole number.

Exercise 3. Loop over the list of offer dicts below and print each company and its salary on one line.

Starting code
Output
(nothing printed)
Hint

Each item o is a dict, so use o["company"].

Show answer
Answer
Output
Bluebell 58000
Quillstone 71000
Fernway 49500

This is how you would go through raw records one at a time before putting them in a table.

2.9 Functions: your own reusable steps

A function is a named set of steps you can use again and again. You make one with def, give it a name and its inputs in brackets, and end the line with a colon. return sends the answer back to whoever called it.

Example
Output
5000.0
4000.0
High
Standard

Common mistakes

  • Using print inside the function instead of return. Then you see the number, but you cannot store it or use it in a sum.
  • Defining the function but never calling it. def only makes it. monthly(60000) runs it.
  • Calling it before the def line. Define first, use after.

Try it

Exercise 1. Write a function pct_change(old, new) that gives back the percentage change, rounded to 1 decimal place. Test it with 50000 and 54000.

Hint

Use the sum from 2.2, inside round(..., 1), after return.

Show answer
Answer
Output
8.0
-5.0

Once it is a function, you can check any pair of numbers in one line. A fall shows as a minus number.

Exercise 2. Write a function clean_city(text) that strips spaces and capitalises. Test it on " dublin" and "CORK ".

Hint

return text.strip().title()

Show answer
Answer
Output
Dublin
Cork

.title() lowers every letter except the first of each word, so it fixes capitals too.

2.10 Importing a library

Python comes with a set of libraries built in (the standard library), such as math and statistics. Others, like pandas, you install with pip first. Either way, you import a library at the top of your file before you use it.

Example
Output
4.0
56500.0
59000
61000

import pandas as pd is how almost everyone writes it, so you will see pd. everywhere.

Common mistakes

  • ModuleNotFoundError: No module named 'pandas': it is not installed, or your virtual environment is not active.
  • Naming your own file pandas.py or statistics.py. Python then imports your file instead of the real library.
  • The install name and the import name are sometimes different: pip install scikit-learn, then import sklearn.

Try it

Exercise 1. Use the statistics library to print the median of [47000, 52000, 90000]. Then print the mean. Why are they so different?

Hint

statistics.median() and statistics.mean().

Show answer
Answer
Output
52000
63000

The median is the middle value. The mean is pulled up by the one big salary. Salaries often have a few big values, so the median is usually the fairer summary.

Exercise 2. Import pandas as pd, make a Series from [3, 8, 5] and print its sum.

Hint

pd.Series([...]).sum(). A Series is one column of data (more in 3.3).

Show answer
Answer
Output
16

A Series has many of the same tools as a list, plus many more.

2.11 Reading an error message

Errors are normal. Everyone gets them, all day. Python's error message is called a traceback, and it tells you exactly what went wrong and where, if you know how to read it. Here is a small file with a mistake in it:

Example prices.py
Output
Dublin 65000
Traceback (most recent call last):
  File "/Users/you/data-practice/prices.py", line 7, in <module>
    show("Galway")
  File "/Users/you/data-practice/prices.py", line 4, in show
    print(city, salaries[city])
KeyError: 'Galway'

Read it from the bottom up.

1. The last line is the most useful: the type of error (KeyError) and the detail ('Galway'). So: you asked a dict for the key Galway, and it is not there.
2. The lines just above show where it happened: line 4, inside show, on print(city, salaries[city]).
3. Further up is how Python got there: line 7 called show("Galway").

Notice the first line of output, Dublin 65000. Python ran every line until the error, then stopped.

The fix depends on what you meant. Add Galway to the dict, or use salaries.get(city, "no data").

Newer versions of Python also draw little ^^^^ marks under the exact part of the line that failed. The Run boxes on this page show File "<exec>" instead of a file name. The bottom line reads the same everywhere.

ErrorWhat it usually means
SyntaxErrorPython cannot read the line: a missing colon, bracket or quote mark.
IndentationErrorThe spaces at the start of a line do not line up.
NameErrorA name you never created, often a typo.
TypeErrorThe wrong kind of value, like adding text to a number.
KeyErrorA key that is not in the dict, or a column that is not in the table.
IndexErrorA position past the end of a list.
ValueErrorThe right kind of value but a bad one, like int("abc").
FileNotFoundErrorThe file is not where Python is looking. Check the name and the folder.
ModuleNotFoundErrorA library that is not installed, or the virtual environment is not active.

Common mistakes

  • Reading from the top and getting lost. Start at the last line.
  • Fixing the line Python points at when the real cause is earlier, such as a variable set to the wrong thing three lines up.
  • Ignoring the error and changing things at random. Read the last line out loud first.

Try it

Exercise 1. Run this. Read the last line of the error. What went wrong, and how would you fix it?

Starting code ex1.py
Output
Traceback (most recent call last):
  File "/Users/you/data-practice/ex1.py", line 2, in <module>
    print(prices[3])
IndexError: list index out of range
Hint

How many items are in the list, and what is the last index?

Show answer
Answer
Output
30

IndexError: list index out of range. Three items means indexes 0, 1 and 2. There is no index 3.

Exercise 2. Run this. What does the last line say, and what is the fix?

Starting code ex2.py
Output
Traceback (most recent call last):
  File "/Users/you/data-practice/ex2.py", line 2, in <module>
    print("Salary: " + salary)
TypeError: can only concatenate str (not "int") to str
Hint

What kinds of value are being joined with +?

Show answer
Answer
Output
Salary: 50000

TypeError: you cannot join a string and an int with +. An f-string, or str(salary), fixes it.

3. Tables with pandas

pandas is the library for working with tables in Python. Everything in this part uses one small practice file.

  1. 3.0 The practice data
  2. 3.1 A DataFrame, and reading a CSV
  3. 3.2 Looking at your data
  4. 3.3 Picking columns
  5. 3.4 Filtering rows
  6. 3.5 Sorting
  7. 3.6 Making new columns
  8. 3.7 Cleaning: missing values and duplicates
  9. 3.8 Reading JSON
  10. 3.9 Group and summarise: groupby
  11. 3.10 Joining tables: merge
  12. 3.11 Working with dates
  13. 3.12 Change over time: pct_change

3.0 The practice data

Made-up data for practice. offers.csv is a small, invented table of 101 job offers at six fictional companies, from 2024 to 2025. Salaries are in euro. Nothing in it is real. Download it into your data-practice folder (or upload it to Colab) to follow along on your own computer. The Run boxes on this page already have it.

ColumnWhat it holds
offer_idA number that should be unique for each offer
companyThe (made-up) company that made the offer
job_familyData Analyst, Data Science or Data Engineering
levelJunior, Mid or Senior
base_salaryYearly base pay in euro
accepted_atThe date the offer was accepted
cityDublin, Cork, Galway, Berlin or Amsterdam

The file has two small problems hidden in it on purpose, the kind real data always has. You will find them in 3.7.

3.1 A DataFrame, and reading a CSV

A CSV file (comma-separated values) is a table saved as plain text. Each line is a row. Commas split the columns. The first line holds the column names. Here are the first three lines of the file, exactly as they look in a text editor:

offers.csv
offer_id,company,job_family,level,base_salary,accepted_at,city
1001,Bluebell,Data Science,Mid,65000,2024-01-02,Amsterdam
1002,Larkspur,Data Science,Senior,72500,2024-01-04,Cork

A DataFrame is pandas' name for a table in Python: rows and columns, each column with a name. Down the left side is the index, a label for each row, which starts at 0. pd.read_csv() reads a CSV file into a DataFrame. By habit it is stored in a variable called df.

Example
Output
   offer_id    company        job_family   level  base_salary accepted_at       city
0      1001   Bluebell      Data Science     Mid      65000.0  2024-01-02  Amsterdam
1      1002   Larkspur      Data Science  Senior      72500.0  2024-01-04       Cork
2      1003  Northwind      Data Analyst     Mid      42000.0  2024-01-15     Galway
3      1004    Fernway  Data Engineering  Junior      47000.0  2024-02-21     Berlin
4      1005    Fernway      Data Analyst  Junior      37000.0  2024-03-04     Dublin

The file must be in the same folder you run Python from. If not, give the full path, like pd.read_csv("/Users/you/Downloads/offers.csv").

Common mistakes

  • FileNotFoundError: the file is not in the folder Python is running in, or the name is spelt differently.
  • Writing df.head without brackets. You get a description of the method instead of the rows.
  • Writing read_csv without pd. in front.

Try it

Exercise 1. Show the first 8 rows instead of 5.

Hint

head() takes a number.

Show answer
Answer
Output
   offer_id      company        job_family   level  base_salary accepted_at       city
0      1001     Bluebell      Data Science     Mid      65000.0  2024-01-02  Amsterdam
1      1002     Larkspur      Data Science  Senior      72500.0  2024-01-04       Cork
2      1003    Northwind      Data Analyst     Mid      42000.0  2024-01-15     Galway
3      1004      Fernway  Data Engineering  Junior      47000.0  2024-02-21     Berlin
4      1005      Fernway      Data Analyst  Junior      37000.0  2024-03-04     Dublin
5      1006     Bluebell      Data Science  Junior      42000.0  2024-03-27     Galway
6      1007      Fernway  Data Engineering  Senior      74500.0  2024-03-27     Galway
7      1008  Harbourline  Data Engineering  Senior      72000.0  2024-03-27       Cork

head(n) shows the first n rows.

Exercise 2. Show the last 3 rows.

Hint

The opposite of head.

Show answer
Answer
Output
     offer_id    company        job_family   level  base_salary accepted_at    city
98       1098    Fernway      Data Analyst     Mid      55000.0  2025-12-29  Dublin
99       1099  Northwind  Data Engineering  Senior      78500.0  2025-12-29    Cork
100      1100   Larkspur      Data Analyst     Mid      50500.0  2025-12-30  Berlin

The index of the last row is 100, so there are 101 rows. Keep that number in mind for 3.7.

3.2 Looking at your data

Before you do anything with a table, look at it. Five checks cover most of what you need to know.

Example
Output
(101, 7)
['offer_id', 'company', 'job_family', 'level', 'base_salary', 'accepted_at', 'city']
offer_id         int64
company         object
job_family      object
level           object
base_salary    float64
accepted_at     object
city            object
dtype: object
city
Dublin       34
Cork         25
Galway       15
Berlin       15
Amsterdam    12
Name: count, dtype: int64

dtypes (data types) uses its own words: int64 is whole numbers, float64 is numbers with decimals, and object is text. Notice that base_salary is float64, even though every salary is a whole number. That is a clue: in pandas, an empty cell forces a number column to become float.

describe() gives a quick summary of every number column:

Example
Output
          offer_id    base_salary
count   101.000000     100.000000
mean   1050.366337   59630.000000
std      28.897309   15844.990924
min    1001.000000   34000.000000
25%    1026.000000   47750.000000
50%    1050.000000   57000.000000
75%    1075.000000   72125.000000
max    1100.000000  101000.000000

Read the count row: offer_id has 101 values but base_salary has 100. One salary is missing. 50% is the median. std (standard deviation) is how spread out the numbers are.

Common mistakes

  • Skipping this step and finding a problem three charts later.
  • Trusting the mean in describe() without checking count: missing values are left out quietly.
  • Expecting dates to be dates. Here accepted_at is object (text) until you convert it in 3.11.

Try it

Exercise 1. How many offers are there in each job family?

Hint

value_counts() on the job_family column.

Show answer
Answer
Output
job_family
Data Analyst        38
Data Science        32
Data Engineering    31
Name: count, dtype: int64

value_counts() sorts from most to least common.

Exercise 2. How many different companies are in the file? Is that what you expected from 3.0?

Hint

nunique() counts unique values. Then look at value_counts() to see them.

Show answer
Answer
Output
7
company
Larkspur       21
Fernway        19
Bluebell       18
Harbourline    15
Quillstone     15
Northwind      12
larkspur        1
Name: count, dtype: int64

Seven, not six. larkspur in lower case is counted as a different company from Larkspur. That is one of the planted problems.

3.3 Picking columns

Put a column name in square brackets to get that column. One column on its own is a Series: a single column of values with an index. To get several columns, put a list of names inside the brackets, which is why you see double brackets.

Example
Output
0    65000.0
1    72500.0
2    42000.0
Name: base_salary, dtype: float64
59630.0
     company       city  base_salary
0   Bluebell  Amsterdam      65000.0
1   Larkspur       Cork      72500.0
2  Northwind     Galway      42000.0

Common mistakes

  • df["company", "city"] with single brackets gives KeyError. Several columns need a list: df[["company", "city"]].
  • A typo in the name, such as df["salary"], gives KeyError: 'salary'. Check df.columns.

Try it

Exercise 1. Show only job_family and level for the first 4 rows.

Hint

Double brackets, then .head(4).

Show answer
Answer
Output
         job_family   level
0      Data Science     Mid
1      Data Science  Senior
2      Data Analyst     Mid
3  Data Engineering  Junior

You can chain steps: pick columns, then take the head.

Exercise 2. What are the highest and lowest base salaries?

Hint

.max() and .min() on the column.

Show answer
Answer
Output
101000.0
34000.0

Both skip the missing value without telling you.

3.4 Filtering rows

To keep only some rows, ask a yes-or-no question about a column. pandas answers it for every row at once, giving a Series of True and False:

Example
Output
0    False
1    False
2    False
3    False
4     True
Name: city, dtype: bool

Put that question inside df[ ] and pandas keeps only the True rows. To combine questions use & for and, | for or, and put each question in its own brackets.

Example
Output
34
        company       city  base_salary
1      Larkspur       Cork      72500.0
23    Northwind     Dublin      78000.0
36     Larkspur     Dublin      78500.0
37     larkspur     Dublin      78500.0
54   Quillstone  Amsterdam      86000.0
66      Fernway  Amsterdam      91000.0
74   Quillstone     Galway      73500.0
75      Fernway       Cork      82500.0
77  Harbourline     Dublin      83000.0
79      Fernway       Cork      79000.0
88     Larkspur       Cork      76500.0
93   Quillstone     Dublin      91000.0
97     Bluebell       Cork      79000.0
27

Common mistakes

  • Using and/or instead of &/| gives ValueError: The truth value of a Series is ambiguous.
  • Leaving out the brackets around each question when you use &.
  • Case: "dublin" matches nothing, because the data says Dublin.

Try it

Exercise 1. How many offers have a base salary above 80000?

Hint

Filter, then len().

Show answer
Answer
Output
11

You could also write (df["base_salary"] > 80000).sum(): True counts as 1.

Exercise 2. Show the Junior offers in Cork.

Hint

Two questions joined by &, each in brackets.

Show answer
Answer
Output
    offer_id     company        job_family   level  base_salary accepted_at  city
12      1013    Bluebell      Data Science  Junior      43500.0  2024-04-29  Cork
13      1014  Quillstone  Data Engineering  Junior      47000.0  2024-05-03  Cork
32      1033    Bluebell      Data Analyst  Junior      36000.0  2024-09-13  Cork
86      1086    Larkspur  Data Engineering  Junior      51500.0  2025-09-25  Cork
87      1087    Bluebell      Data Analyst  Junior      39500.0  2025-09-28  Cork

Both questions must be True for a row to stay.

Exercise 3. How many offers are not in Dublin?

Hint

!= means not equal.

Show answer
Answer
Output
67

34 rows are in Dublin (one of them is the duplicate), so 101 - 34 = 67.

3.5 Sorting

sort_values() sorts rows by a column, smallest first. Add ascending=False for biggest first.

Example
Output
        company   level       city  base_salary
94  Harbourline  Senior  Amsterdam     101000.0
66      Fernway  Senior  Amsterdam      91000.0
93   Quillstone  Senior     Dublin      91000.0
29  Harbourline  Senior  Amsterdam      90000.0
31     Bluebell  Senior     Dublin      89000.0
         city  base_salary
17  Amsterdam      50000.0
73  Amsterdam      57000.0
33  Amsterdam      64000.0
0   Amsterdam      65000.0

Sorting does not change df itself. It gives back a sorted copy, so store it in a new name if you want to keep it. Missing values always go to the end.

Common mistakes

  • Expecting df.sort_values(...) on its own line to change df. Store the result.
  • Sorting dates stored as text. It works here only because the dates are written year-month-day.

Try it

Exercise 1. Show the 3 lowest salaries, with company and job family.

Hint

Sort smallest first, then pick columns and take the head.

Show answer
Answer
Output
      company    job_family  base_salary
42   Bluebell  Data Analyst      34000.0
72  Northwind  Data Analyst      35000.0
35   Larkspur  Data Analyst      35500.0

df.nsmallest(3, "base_salary") does the same in one step.

Exercise 2. Show the 5 most recently accepted offers.

Hint

Sort by accepted_at, newest first.

Show answer
Answer
Output
     offer_id    company        job_family   level  base_salary accepted_at    city
100      1100   Larkspur      Data Analyst     Mid      50500.0  2025-12-30  Berlin
99       1099  Northwind  Data Engineering  Senior      78500.0  2025-12-29    Cork
98       1098    Fernway      Data Analyst     Mid      55000.0  2025-12-29  Dublin
97       1097   Bluebell      Data Science  Senior      79000.0  2025-12-24    Cork
96       1096    Fernway      Data Analyst  Senior      68500.0  2025-11-15  Berlin

The index numbers stay with their rows, which is why they now look out of order.

3.6 Making new columns

To add a column, give it a new name in square brackets and set it with =. Maths on a column happens to every row at once.

Example
Output
  company_clean   level  base_salary  monthly  is_senior
0      Bluebell     Mid      65000.0   5417.0      False
1      Larkspur  Senior      72500.0   6042.0       True
2     Northwind     Mid      42000.0   3500.0      False
3       Fernway  Junior      47000.0   3917.0      False
4       Fernway  Junior      37000.0   3083.0      False

.str lets you use the string methods from 2.3 on a whole column. For your own rule, write a function and pass it to .apply(), which runs it on every value:

Example
Output
band
Standard    73
High        28
Name: count, dtype: int64

Careful: the row with no salary was counted as Standard, because a missing value is not >= 70000. Clean first, then build columns. That is next.

Common mistakes

  • df.monthly = ... with a dot does not make a new column. Use df["monthly"] = ....
  • Calling string methods on a column without .str: df["company"].title() gives AttributeError.

Try it

Exercise 1. Add a column salary_k holding the salary in thousands (65000 becomes 65.0). Show company and salary_k for the first 3 rows.

Hint

Divide the column by 1000.

Show answer
Answer
Output
     company  salary_k
0   Bluebell      65.0
1   Larkspur      72.5
2  Northwind      42.0

Thousands are easier to read on charts.

Exercise 2. Add a column city_upper with the city in capitals. Show the first 3 values.

Hint

.str.upper()

Show answer
Answer
Output
0    AMSTERDAM
1         CORK
2       GALWAY
Name: city_upper, dtype: object

Any string method from 2.3 works after .str.

3.7 Cleaning: missing values and duplicates

Real data always has problems. Two of the most common are missing values (empty cells) and duplicates (the same thing recorded twice). pandas shows an empty cell as NaN, short for “not a number”.

Example
Output
offer_id       0
company        0
job_family     0
level          0
base_salary    1
accepted_at    0
city           0
dtype: int64
    offer_id   company        job_family level  base_salary accepted_at    city
52      1052  Larkspur  Data Engineering   Mid          NaN  2025-01-30  Galway

One missing salary, offer 1052. Now duplicates. Every offer_id should appear once:

Example
Output
1
    offer_id   company    job_family   level  base_salary accepted_at    city
36      1037  Larkspur  Data Science  Senior      78500.0  2024-09-28  Dublin
37      1037  larkspur  Data Science  Senior      78500.0  2024-09-28  Dublin

Offer 1037 appears twice. The second copy has the company in lower case, so the rows are not quite identical. That is why plain df.drop_duplicates() would miss it. Tell it which column should be unique with subset:

Example
Output
101 rows before, 99 after

You have three choices for a missing value: drop the row (dropna), fill it (fillna, often with the median), or keep it and let pandas skip it. Dropping is honest when only a few rows are missing. Filling invents a number, so say so if you do it.

From here on, every example starts with these four lines, so you always work from clean data:

The clean start
import pandas as pd
df = pd.read_csv("offers.csv")
df = df.drop_duplicates(subset="offer_id")   # remove the repeated offer
df = df.dropna(subset=["base_salary"])       # remove the offer with no salary

Common mistakes

  • df.dropna() with no subset drops a row if any column is empty, which can throw away far more than you meant.
  • Forgetting to store the result: df.dropna() on its own line changes nothing.
  • Filling missing salaries with 0. That drags every average down.

Try it

Exercise 1. Instead of dropping it, fill the missing salary with the median salary. Check there are no missing salaries left.

Hint

df["base_salary"].fillna(...), with df["base_salary"].median() inside.

Show answer
Answer
Output
57000.0
0

0 missing now. Whether filling is right depends on the question: for “median by city” it slightly pulls that city toward the overall median.

Exercise 2. Does df.drop_duplicates(), with no subset, remove the repeated offer? Check by counting rows.

Hint

Compare len(df) before and after.

Show answer
Answer
Output
101 101

No: 101 both times. The two copies differ in the company name, so they are not exact duplicates. Decide which column must be unique and use subset.

Exercise 3. Fix the lower-case company name instead, so nunique() on company gives 6.

Hint

.str.title() on the company column, stored back into it.

Show answer
Answer
Output
6

Tidy text first, then rows that were near-duplicates become exact ones. Here you would still drop the repeat by offer_id.

3.8 Reading JSON

Not all data comes as a CSV. Websites and apps usually send data as JSON (JavaScript Object Notation). JSON is plain text too, but it can hold data inside data. It uses only a few building blocks:

• An object, in curly brackets { }: names and values, like a Python dict. Each name is a key, always in double quote marks.
• A list (JSON calls it an array), in square brackets [ ], like a Python list.
• Simple values: text in double quotes, numbers, true/false, and null for empty.
• Nesting: a value can itself be an object or a list. That is what makes JSON different from a flat table.

Here is the first offer in offers.json (made up, like the CSV). The company and comp (compensation: base pay, equity and bonus) values are objects nested inside the offer:

offers.json (first record)
  {
    "offer_id": 1,
    "role": "Data Analyst",
    "level": "Mid",
    "company": {
      "name": "Fernway",
      "city": "Cork"
    },
    "comp": {
      "base": 52000,
      "equity": 0,
      "bonus": 3000
    }
  },
  {

Python's built-in json library turns JSON text into Python lists and dicts. with open(...) as f opens the file and closes it again when the indented block ends.

Example
Output
<class 'list'> 6
Data Analyst
Fernway
52000

To get a table, use pd.json_normalize(). It flattens the nesting: each offer becomes one row, and each nested key becomes its own column, named with a dot, like company.name.

Example
Output
['offer_id', 'role', 'level', 'company.name', 'company.city', 'comp.base', 'comp.equity', 'comp.bonus']
   offer_id company.name  comp.base  comp.bonus
0         1      Fernway      52000      3000.0
1         2   Quillstone      84000      8000.0
2         3     Larkspur      50500         NaN
3         4     Bluebell      68000      4000.0
4         5    Northwind      66000      5000.0
5         6  Harbourline      60500      2500.0

JSON's null became NaN: offer 3 has no bonus. Everything from 3.2 to 3.7 now works on flat, as it is an ordinary DataFrame. If a JSON file is already flat (no nesting), pd.read_json("file.json") reads it in one step.

Common mistakes

  • Using json.load on a string, or json.loads on a file. load reads a file; loads (load string) reads text.
  • Expecting single quote marks to work in JSON. JSON needs double quotes.
  • Adding nested columns with a missing value: comp.base + comp.bonus gives NaN for any row where bonus is empty. Fill first.

Try it

Exercise 1. Without pandas, print the city of the third offer in offers.json.

Hint

Third item is data[2]. City is inside company.

Show answer
Answer
Output
Berlin

Read it left to right: the list, then item 2, then the company object, then its city.

Exercise 2. Flatten the file and add a total column: base + equity + bonus, counting a missing bonus as 0. Show company, role and total, highest first.

Hint

.fillna(0) on comp.bonus before adding.

Show answer
Answer
Output
  company.name              role     total
1   Quillstone      Data Science  102000.0
3     Bluebell      Data Science   77000.0
4    Northwind      Data Analyst   75000.0
5  Harbourline  Data Engineering   63000.0
0      Fernway      Data Analyst   55000.0
2     Larkspur  Data Engineering   52500.0

Here 0 is a fair fill: no bonus listed most likely means no bonus. Without the fill, offer 3's total would be NaN.

3.9 Group and summarise: groupby

Most data questions sound like “what is the average X for each Y?”. groupby answers them in three steps: split the rows into groups, apply a sum to each group, and combine the answers into a new table.

Example
Output
job_family
Data Analyst        46250.0
Data Engineering    67500.0
Data Science        63500.0
Name: base_salary, dtype: float64
                  count     mean   median
job_family                               
Data Analyst         38  47987.0  46250.0
Data Engineering     30  67750.0  67500.0
Data Science         31  65435.0  63500.0

Read the first one as: group by job family, take the salary column, give the median of each group. .agg() (aggregate) takes a list of summaries and gives one column for each. Common ones are count, sum, mean, median, min and max.

You can group by more than one column. In SQL this is GROUP BY job_family, level.

Example
Output
job_family        level 
Data Analyst      Junior    38000.0
                  Mid       49250.0
                  Senior    65500.0
Data Engineering  Junior    50250.0
                  Mid       67500.0
                  Senior    83500.0
Data Science      Junior    49500.0
                  Mid       58500.0
                  Senior    79000.0
Name: base_salary, dtype: float64
     job_family   level  base_salary
0  Data Analyst  Junior      38000.0
1  Data Analyst     Mid      49250.0
2  Data Analyst  Senior      65500.0

Common mistakes

  • Forgetting to pick a column, so pandas tries to summarise every column, including text ones.
  • Grouping before cleaning. The lower-case larkspur would be its own group.
  • Ignoring count. A median from 2 offers is not worth much. Always check how many rows are in each group.

Try it

Exercise 1. How many offers are there in each city?

Hint

Group by city and use size(), or value_counts().

Show answer
Answer
Output
city
Amsterdam    12
Berlin       15
Cork         25
Dublin       33
Galway       14
dtype: int64

size() counts rows in each group. Groups come out in alphabetical order.

Exercise 2. What is the mean salary for each level, rounded, highest first?

Hint

groupby, mean, .round(0), then sort_values(ascending=False).

Show answer
Answer
Output
level
Senior    77467.0
Mid       57325.0
Junior    43707.0
Name: base_salary, dtype: float64

You can chain several steps on one line. Read it left to right.

Exercise 3. For each company, show the number of offers and the median salary.

Hint

.agg(["count", "median"])

Show answer
Answer
Output
             count   median
company                    
Bluebell        18  50000.0
Fernway         19  55000.0
Harbourline     15  60000.0
Larkspur        20  59500.0
Northwind       12  54000.0
Quillstone      15  64000.0

Six companies, because the clean start removed the lower-case copy.

3.10 Joining tables: merge

Data often sits in more than one table. merge joins two tables using a column they share, called the key. It is the same idea as a JOIN in SQL: df.merge(companies, on="company", how="left") is LEFT JOIN companies ON company.

Here is a second small table, typed straight into the code, with each company's sector. Fernway is left out on purpose.

Example
Output
   offer_id    company   sector
0      1001   Bluebell   Health
1      1002   Larkspur  Finance
2      1003  Northwind   Retail
3      1004    Fernway      NaN
4      1005    Fernway      NaN
19 offers have no sector
how=KeepsSQL
"left"Every row of the left table. No match means NaN.LEFT JOIN
"inner"Only rows that match in both tables.INNER JOIN
"right"Every row of the right table.RIGHT JOIN
"outer"Every row of both.FULL OUTER JOIN

Common mistakes

  • Not checking row counts before and after. If the key repeats in both tables, a merge makes extra rows.
  • Keys that look the same but are not, like Larkspur and larkspur, or a number stored as text in one table.
  • Using the default how="inner" without noticing it dropped rows.

Try it

Exercise 1. Using the companies table above, what is the median salary for each sector?

Hint

Merge, then groupby sector.

Show answer
Answer
Output
sector
Finance    63000.0
Health     50000.0
Retail     54000.0
Travel     60000.0
Name: base_salary, dtype: float64

groupby leaves out rows where the sector is NaN, so Fernway's offers are quietly missing. Say so when you report it.

Exercise 2. How many offers does an inner join keep, compared with the left join?

Hint

len() of each.

Show answer
Answer
Output
99
80

The inner join drops Fernway's 19 offers, because Fernway is not in the companies table.

3.11 Working with dates

In the CSV, dates are just text. pd.to_datetime() turns them into real dates, so pandas knows that March comes after February. Then .dt gives you date tools, the same way .str gives you text tools.

Example
Output
datetime64[ns]
  accepted_at  year  quarter  period
0  2024-01-02  2024        1  2024Q1
1  2024-01-04  2024        1  2024Q1
2  2024-01-15  2024        1  2024Q1
3  2024-02-21  2024        1  2024Q1
4  2024-03-04  2024        1  2024Q1
period
2024Q1     9
2024Q2    12
2024Q3    17
2024Q4    11
2025Q1    12
2025Q2    12
2025Q3    13
2025Q4    13
Freq: Q-DEC, dtype: int64

A quarter is three months: Q1 is January to March, Q2 April to June, and so on. to_period("Q") keeps the year with the quarter, so 2024 Q1 and 2025 Q1 stay apart. Use "M" for months.

Common mistakes

  • Grouping on dt.quarter alone, which mixes Q1 2024 with Q1 2025. Use to_period("Q").
  • Dates written day-first, like 03/04/2025. Tell pandas: pd.to_datetime(col, dayfirst=True).
  • Forgetting to convert, then getting AttributeError: Can only use .dt accessor with datetimelike values.

Try it

Exercise 1. How many offers were accepted in each month of 2025?

Hint

Convert, filter to year 2025, then group by dt.month.

Show answer
Answer
Output
accepted_at
1     2
2     3
3     7
4     6
5     2
6     4
7     2
8     2
9     9
10    6
11    3
12    4
dtype: int64

You can group by a Series you work out on the spot, not only by a column name.

Exercise 2. On which day of the week were the most offers accepted?

Hint

.dt.day_name(), then value_counts().

Show answer
Answer
Output
accepted_at
Monday       23
Tuesday      18
Wednesday    14
Saturday     14
Thursday     12
Friday       10
Sunday        8
Name: count, dtype: int64

The data is made up, so this is just practice. With real data it can show when people decide.

3.12 Change over time: pct_change

pct_change() works out the change from one row to the next, as a share. Times 100 makes it a percentage. On a table of quarters, that is the quarter-on-quarter change.

Example
Output
         median  qoq_pct
period                  
2024Q1  65000.0      NaN
2024Q2  50750.0    -21.9
2024Q3  58500.0     15.3
2024Q4  55000.0     -6.0
2025Q1  55000.0      0.0
2025Q2  60000.0      9.1
2025Q3  63000.0      5.0
2025Q4  67500.0      7.1

The first quarter shows NaN because there is no quarter before it to compare with. pct_change(4) compares with four rows back: with quarters, that is year-on-year.

Notice how much the median jumps around. Each quarter has only 9 to 17 offers, so a few big or small offers move it a lot. With small groups, look at the trend over several quarters, not one jump.

Common mistakes

  • Running pct_change on unsorted rows. Sort by date first (groupby on a period sorts for you).
  • Missing quarters. If a quarter has no rows, it is skipped and the next change spans six months.
  • Saying “up 10%” when you mean 10 percentage points. 20% to 30% is up 10 points, or up 50%.

Try it

Exercise 1. Work out the quarter-on-quarter change in the number of offers.

Hint

Group by period and use size(), then pct_change().

Show answer
Answer
Output
period
2024Q1     NaN
2024Q2    33.3
2024Q3    41.7
2024Q4   -35.3
2025Q1     9.1
2025Q2     0.0
2025Q3     8.3
2025Q4     0.0
Freq: Q-DEC, dtype: float64

Same method, different measure. Small counts give big percentages.

Exercise 2. Work out the year-on-year change in median salary for each quarter of 2025.

Hint

pct_change(4), then drop the empty rows.

Show answer
Answer
Output
period
2025Q1   -15.4
2025Q2    18.2
2025Q3     7.7
2025Q4    22.7
Freq: Q-DEC, Name: base_salary, dtype: float64

The 2024 quarters have nothing four quarters back, so they are NaN and dropna() removes them.

4. Charts with matplotlib

A chart turns a table into something people understand in a second. matplotlib is the standard charting library in Python.

  1. 4.1 Your first line chart
  2. 4.2 A bar chart

4.1 Your first line chart

A line chart shows how one number changes over time. Every matplotlib chart has two parts: the figure (fig), the whole image, and the axes (ax), the box with the chart in it. plt.subplots() makes both. You then draw on ax.

Example
Output
(nothing printed)
Chart made by the code above

q.index.astype(str) turns periods like 2024Q1 into plain text labels. savefig writes the picture to a file. Call it before plt.show(), because closing the window can leave an empty figure behind.

One clear headline per chart. The title should say what the reader should see, not just what the chart is. “Median salary by quarter” labels it. “Median salary climbed through 2025” tells them the point. Check the headline is true for the data: the 2025 quarters went 55,000, 60,000, 63,000, 67,500.

4.2 A bar chart

A bar chart compares groups. Sort the bars so the order means something. Sideways bars (barh) leave room for long labels and read well on a phone.

Example
Output
(nothing printed)
Chart made by the code above

Common mistakes

  • No title or axis labels. Anyone looking at the chart has to guess.
  • A title that only names the chart instead of saying what it shows.
  • Bars that do not start at zero. Bar length is the whole message, so a cut axis makes small gaps look big. (Line charts can start elsewhere.)
  • Bars in random order. Sort them.
  • Calling plt.show() before savefig() and getting a blank PNG.

Try it

Exercise 1. Make a bar chart of the number of offers in each city, sorted, with a headline title. Save it as offers-by-city.png.

Hint

value_counts(), then .sort_values(), then ax.barh.

Show answer
Answer
Output
(nothing printed)
Chart made by the code above

Sorting smallest first puts the biggest bar at the top in barh.

Exercise 2. Make a line chart of the number of offers per quarter, with labels, and save it.

Hint

Same as 4.1, with size() instead of the median.

Show answer
Answer
Output
(nothing printed)
Chart made by the code above

set_ylim(0, None) starts the axis at zero, so a change from 12 to 17 does not look huge.

5. Ten practice tasks

Interview-style tasks on offers.csv, easiest first. Each one starts from the clean start in 3.7. Try each before you open the answer. In an interview, say what you are checking as you go: missing values, duplicates, and how many rows are in each group.

  1. The tasks

The tasks

Task 1. How many offers are left after cleaning?

Hint

len(df) after the clean start.

Show answer
Answer
Output
99

101 rows, minus one duplicate and one missing salary, leaves 99.

Task 2. Which company made the most offers?

Hint

value_counts() sorts most common first; .head(1).

Show answer
Answer
Output
company
Larkspur    20
Name: count, dtype: int64

Larkspur, with 20. Check for ties by looking at the top few.

Task 3. What is the median base salary for each job family?

Hint

groupby, then median().

Show answer
Answer
Output
job_family
Data Analyst        46250.0
Data Engineering    67500.0
Data Science        63500.0
Name: base_salary, dtype: float64

The median is less pulled by a few very high offers than the mean.

Task 4. What share of offers is in each city, as a percentage?

Hint

value_counts(normalize=True) gives shares that add up to 1.

Show answer
Answer
Output
city
Dublin       33.3
Cork         25.3
Berlin       15.2
Galway       14.1
Amsterdam    12.1
Name: proportion, dtype: float64

normalize=True divides each count by the total.

Task 5. What is the mean and median salary for each level, and how many offers are in each?

Hint

.agg(["count", "mean", "median"])

Show answer
Answer
Output
        count     mean   median
level                          
Junior     29  43707.0  42000.0
Mid        40  57325.0  56500.0
Senior     30  77467.0  78500.0

Showing the count next to each average is a good habit.

Task 6. Which city pays the most for Data Science at Senior level?

Hint

Filter to both, then group by city. Look at the count too.

Show answer
Answer
Output
           count   median
city                     
Amsterdam      2  88500.0
Dublin         4  80750.0
Cork           5  79000.0
Galway         1  73500.0

Amsterdam has the highest median, but from only 2 offers. A good answer says that, rather than just naming the city.

Task 7. What is the highest-paid offer in each job family?

Hint

Sort by salary, highest first, then keep the first row of each group with groupby(...).head(1).

Show answer
Answer
Output
          job_family      company   level       city  base_salary
94  Data Engineering  Harbourline  Senior  Amsterdam     101000.0
66      Data Science      Fernway  Senior  Amsterdam      91000.0
53      Data Analyst      Fernway  Senior     Dublin      69000.0

Sort first, then head(1) in each group keeps each group's top row.

Task 8. How many offers were accepted in each quarter?

Hint

to_period("Q"), then groupby and size().

Show answer
Answer
Output
period
2024Q1     9
2024Q2    12
2024Q3    17
2024Q4    11
2025Q1    12
2025Q2    12
2025Q3    13
2025Q4    13
Freq: Q-DEC, dtype: int64

Use a period, not dt.quarter, so the two years stay apart.

Task 9. What is the quarter-on-quarter change in median salary?

Hint

Median per period, then pct_change().

Show answer
Answer
Output
period
2024Q1     NaN
2024Q2   -21.9
2024Q3    15.3
2024Q4    -6.0
2025Q1     0.0
2025Q2     9.1
2025Q3     5.0
2025Q4     7.1
Freq: Q-DEC, Name: base_salary, dtype: float64

The first quarter is NaN because there is nothing before it. Mention the small group sizes before reading much into one jump.

Task 10. Plot the median salary trend by quarter for Data Science only, give it a headline, and save it as a PNG.

Hint

Filter first, then the 4.1 chart.

Show answer
Answer
Output
period
2024Q1    65000.0
2024Q2    50000.0
2024Q3    61250.0
2024Q4    55000.0
2025Q1    71500.0
2025Q2    63000.0
2025Q3    80750.0
2025Q4    79000.0
Freq: Q-DEC, Name: base_salary, dtype: float64
Chart made by the code above

.copy() makes the filtered table its own table, so adding a column to it does not trigger a pandas warning. Print the numbers before you write the headline, so the headline matches them.

6. Glossary

Argument / input
A value you pass into a function, inside its brackets.
Boolean
True or False.
CSV
Comma-separated values: a table saved as plain text.
DataFrame
pandas' table: rows, named columns and an index.
dict
Values stored under keys, in { }.
dtype
The kind of data in a column: int64, float64, object (text), datetime64.
f-string
Text with f in front, where {name} is filled in.
float
A number with a decimal point.
Function
A named set of steps. Made with def, run with brackets.
groupby
Split rows into groups, summarise each, combine the results.
Import
Load a library so you can use it.
Index
A position in a list (from 0), or the row labels of a DataFrame.
int
A whole number.
Interpreter
The program that reads and runs your Python.
JSON
A text format for data with nesting: objects { }, lists [ ] and values.
Library
Ready-made code you can use, like pandas or matplotlib.
list
Values in order, in [ ].
Loop
Lines that repeat, once for each item.
merge
Join two tables on a shared column. Like SQL's JOIN.
Method
A function attached to a value, called with a dot: text.upper().
NaN
pandas' mark for a missing value.
Notebook
A document of code cells with output under each, like Jupyter or Colab.
pip
The tool that installs libraries.
Series
One column of data with an index.
String
Text, in quote marks.
Terminal
A window for typing commands to your computer.
Traceback
Python's error message. Read it from the bottom up.
Variable
A name that holds a value.
Virtual environment
A private box of libraries for one project (.venv).

The practice data on this page is made up. See also Data interview questions.