Edexcel International Advanced Level Computer Science, point 18.1.4
Pandas is a third-party library for analysing tabular data (rows and columns, like a spreadsheet). It is installed separately (pip install pandas), and imported as pd. Its main object is the DataFrame. Check the Programming Language Subset (PLS) for the functions allowed.
import pandas as pd
Key objects
| Object | Meaning |
|---|---|
| DataFrame | A table: rows with labels (index) and columns with names; each column can hold a different type |
| Series | A single column (or row) of a DataFrame |
The examples use a small file, students.csv:
name,form,mark,age
Amy,12A,72,17
Raj,12B,91,18
Sam,12A,58,17
Li,12B,,18
Zoe,12A,85,17
Raj,12B,91,18
(Li has a missing mark, and Raj appears twice.)
a. Load CSV
df = pd.read_csv("students.csv")
print(df)
name form mark age
0 Amy 12A 72.0 17
1 Raj 12B 91.0 18
2 Sam 12A 58.0 17
3 Li 12B NaN 18
4 Zoe 12A 85.0 17
5 Raj 12B 91.0 18
read_csvturns each CSV row into a DataFrame row. Missing values appear asNaN("not a number"), and make the column a float.- Useful options:
sep=";"(another separator),header=None,usecols=[...],index_col="name". - Handle
FileNotFoundError.
Selecting data
print(df["mark"]) # one column (a Series)
print(df[["name", "mark"]]) # several columns
print(df.iloc[0]) # row 0 (by position)
# rows where the condition is true
print(df[df["mark"] > 80])
# ['Amy', 'Sam', 'Zoe']
print(df[df["form"] == "12A"]["name"].tolist())
b. Measures of central tendency
Averages that describe the typical value:
marks = df["mark"]
print(marks.mean()) # 79.4 (the mean)
print(marks.median()) # 85.0 (the middle value)
# 91.0 (the most common value)
print(marks.mode()[0])
| Measure | Meaning | Note |
|---|---|---|
| Mean | Sum divided by the count | Affected by extreme values; missing values are skipped |
| Median | The middle value when sorted | Not affected by outliers |
| Mode | The most frequent value | There can be several (mode() returns a Series) |
Check: the valid marks are 72, 91, 58, 85, 91 (Li's is missing), so mean , median (sorted 58, 72, 85, 91, 91) is 85, and mode is 91.
Group by a column:
print(df.groupby("form")["mark"].mean())
# form
# 12A 71.666667
# 12B 91.000000
c. Information about data
print(df.shape) # (6, 4): rows, columns
# ['name', 'form', 'mark', 'age']
print(df.columns.tolist())
print(df.dtypes) # the type of each column
# types and non-missing counts
df.info()
print(df.head(3)) # the first 3 rows
# count, mean, std, min, quartiles, max
print(df["mark"].describe())
print(df.isna().sum()) # missing values per column
# how often each value appears
print(df["form"].value_counts())
describe() gives count, mean, standard deviation, minimum, quartiles (25%, 50%, 75%) and maximum, which summarises the spread of the data.
d. Clean data
Real data is messy (6.1.2). Common steps:
# 1. find missing values
print(df["mark"].isna().sum()) # 1
# 2a. drop rows with missing values
cleaned = df.dropna(subset=["mark"])
# 2b. or fill them (here with the median)
filled = df.copy()
filled["mark"] = filled["mark"].fillna(filled["mark"].median())
# 3. remove duplicate rows
cleaned = cleaned.drop_duplicates()
# 4. fix types
cleaned["mark"] = cleaned["mark"].astype(int)
# 5. tidy text
cleaned["name"] = cleaned["name"].str.strip().str.title()
# 6. remove impossible values
cleaned = cleaned[(cleaned["mark"] >= 0) & (cleaned["mark"] <= 100)]
print(cleaned)
| Problem | Method |
|---|---|
| Missing values | dropna(), fillna(value) |
| Duplicates | drop_duplicates() |
| Wrong type | astype(...), pd.to_numeric(..., errors="coerce") |
| Messy text | .str.strip(), .str.lower(), .str.replace(...) |
| Out-of-range values | Filter with a condition |
| Wrong column names | df.rename(columns={...}) |
Which to choose for missing values? Dropping loses data, but fills (mean or median) add assumptions. Say what you did and why.
e. Load and save text files
cleaned.to_csv("students_clean.csv", index=False) # save as CSV
again = pd.read_csv("students_clean.csv") # load it again
print(again.shape) # (4, 4)
to_csv(filename, index=False)writes the table (index=Falseleaves out the row numbers).read_csvloads it back.pd.read_table/read_csv(sep="\t")read tab-separated text.- Other formats:
to_json,to_excel.
Pandas compared with NumPy
| Pandas DataFrame | NumPy array | |
|---|---|---|
| Structure | Labelled rows and columns | Plain grid of numbers |
| Column types | Different per column | One type |
| Missing data | Handled (NaN, dropna) |
Limited |
| Best for | Real-world tables, CSV files | Fast numerical maths |
(Pandas is built on NumPy.)
Worked example
Task: analyse the class file: clean it, report the mean mark per form, and save the cleaned data.
import pandas as pd
from io import StringIO
csv_text = """name,form,mark,age
Amy,12A,72,17
Raj,12B,91,18
Sam,12A,58,17
Li,12B,,18
Zoe,12A,85,17
Raj,12B,91,18
"""
df = pd.read_csv(StringIO(csv_text)) # (normally a filename)
# remove the repeated Raj row
df = df.drop_duplicates()
df = df.dropna(subset=["mark"]) # remove Li (no mark)
df["mark"] = df["mark"].astype(int) # whole numbers
print(df.shape) # (4, 4)
print(df["mark"].mean()) # 76.5
# 12A 71.666667, 12B 91.0
print(df.groupby("form")["mark"].mean())
df.to_csv("students_clean.csv", index=False)
Check: after cleaning, the marks are 72, 91, 58, 85, so the mean is . Form 12A has 72, 58, 85 (mean 71.67), and form 12B has 91 only.
Exam tip: know the steps: load, inspect (shape, describe, isna), clean (dropna, fillna, drop_duplicates), analyse (mean, median, groupby), save (to_csv). Remember that missing values are NaN, and justify your cleaning choices. Compare mean and median to spot outliers.
Check yourself
What is a DataFrame?
A table in Pandas with labelled rows and named columns, where each column can hold a different type.
How are missing values shown, and how can you remove rows that have them?
As NaN. Use dropna() to remove the rows (or fillna() to replace the values).
What is the median of 4, 9, 11, 20, 30?
11, the middle value.
Which method gives a summary of count, mean, spread and quartiles?
describe().
Why use index=False when saving with to_csv?
It stops the row numbers being written as an extra column in the file.