Skip to content
Analyzing and Visualizing Data

Tables and DataFrames


Learning Objectives

  • You can relate a DataFrame to dictionary records and a CSV table.
  • You can read a CSV and inspect its rows, columns, dimensions, and types.
  • You can explain what one observation and each measurement represent.

In Part 5, a CSV reader built a list of dictionary records. The pandas library provides a DataFrame, a table whose columns have names. Pandas can read a CSV into a DataFrame and carry out operations on its columns without a separate loop for each calculation.

We will use a synthetic dataset of study sessions. Each row records one session, with its subject and duration in minutes. The values are examples for analysis, rather than measurements of students on this course.

Python Environment Setup

Create a folder named data-analysis and open it in your IDE. Use Python 3.11 or newer, as in Part 7. Create requirements.txt with:

pandas==3.0.2
matplotlib==3.10.8
seaborn==0.13.2
The Packages in This Environment

Pandas provides the tables and calculations. Seaborn draws the charts introduced later in this part. Matplotlib supplies the figure containing a chart and the methods for labeling and saving it.

As in Part 7, .venv keeps this project’s packages separate from other projects. This is a new environment for data-analysis; reuse it throughout Part 8. The file requirements.txt records the package versions to install.

Open a terminal in data-analysis. Create the environment once, then activate it. In Windows PowerShell:

py -m venv .venv
.\.venv\Scripts\Activate.ps1

On macOS/Linux:

python3 -m venv .venv
source .venv/bin/activate

In the activated environment, install the packages:

pip install -r requirements.txt

Activation makes python use the project’s interpreter in this terminal. In each new terminal, open data-analysis and repeat only the activation line; the environment and packages are already present. If activation fails or venv is unavailable, use the troubleshooting notes in Part 7’s environment setup.

Records in a DataFrame

Create analysis.py beside requirements.txt:

import pandas as pd
records = [
{"subject": "Programming", "minutes": 25},
{"subject": "Mathematics", "minutes": 40},
{"subject": "Programming", "minutes": 15}
]
sample = pd.DataFrame(records)
print(sample)

import pandas as pd imports the library using the conventional short name pd. The call pd.DataFrame(records) creates a table from the list. The dictionary keys become column names, and each dictionary becomes a row.

Save the file and run it in the activated terminal:

python analysis.py

The output is:

subject minutes
0 Programming 25
1 Mathematics 40
2 Programming 15

The leftmost values, 0, 1, and 2, are the table’s index labels. Pandas created these row labels; they are not a third field in the original records. The table has three observations and two recorded columns. Repeated subject names still represent separate sessions.

Rows and Measurements

0 / 5 points

A CSV records one journey per data row:

mode,minutes,distance_km
walk,12,0.8
bus,18,5.4
bus,22,6.1

Which pair gives the number of recorded journeys and their total duration in minutes?

Reading the Study Session CSV

Create sessions.csv in data-analysis and copy the following contents into it:

subject,minutes
Programming,25
Mathematics,40
Languages,10
Writing,15
Programming,20
Mathematics,45
Languages,15
Programming,30
Writing,25
Mathematics,50
Programming,30
Languages,20
Programming,35
Mathematics,55
Programming,35
Languages,25
Writing,110
Programming,40
Mathematics,60
Programming,40
Languages,30
Programming,45
Mathematics,65
Programming,50

This is a larger dataset than the three-record example above. It contains 24 sessions. Replace analysis.py with:

import pandas as pd
sessions = pd.read_csv("sessions.csv")
print(sessions.head())
print(sessions.shape)

Save and run the script using the same command as before. Run it from data-analysis so that the relative filename sessions.csv refers to the file beside the script.

The output is:

subject minutes
0 Programming 25
1 Mathematics 40
2 Languages 10
3 Writing 15
4 Programming 20
(24, 2)

pd.read_csv reads the header as column names and builds the DataFrame. sessions.head() returns the first five rows for inspection; it does not remove the remaining rows. The shape attribute contains the number of rows followed by the number of columns. Here, (24, 2) describes 24 observations with two fields each.

Give head a number to choose how many rows to inspect: sessions.head(3) returns the first three rows. This changes only the preview, not the table stored in sessions.

As with the objects in Part 6, attributes and methods have different notation. Use sessions.shape to read the attribute and sessions.head() to call the method.

Blank lines in a CSV do not create observations. A file containing only its header produces an empty table with the named columns, so its row count is zero.

Inspecting Columns and Types

Add these lines to analysis.py:

print("Columns:", list(sessions.columns))
print(sessions.dtypes)
print("Loaded rows:", len(sessions))

columns contains the names subject and minutes. dtypes reports the types pandas chose for the columns: subject names are text, and the complete duration column contains integers. The exact type names printed for text can depend on the pandas version. In the installed version, the duration column is reported as int64.

len(sessions) is 24: it counts rows. It does not count the distinct subjects, include the header as a session, or multiply the number of rows by the number of columns.

Using Print to Inspect the Data

The labelled prints show Columns: ['subject', 'minutes'] and Loaded rows: 24. Together with head(), they help you inspect the values your calculation is using. For example, an unexpected row count is a reason to check the contents and location of sessions.csv before changing a calculation.

Save the file and run python analysis.py again after each change. This is an ordinary script: each run reads the CSV and executes the file from the beginning. There is no running web server to refresh.

Practise the notation by making one small change in each supplied Python program. Each handout states what to change and what the change does. Each step supplies a separate main.py and any small CSV files it needs. Use Submit to check these programs; the browser’s Run does not load the libraries.

Index labels identify rows within a table. The labels need not be consecutive. The number of observations comes from the rows present, rather than from the largest displayed label.

Reading a Table

0 / 5 points

A DataFrame displays two recorded room sessions:

room minutes
11 East 25
17 West 40

Each observation is one room session. Which description matches the displayed table?

The next exercise uses a CSV of journeys. Apply the same row-and-column model: one journey occupies one row, even when several journeys have the same travel mode.

Counting Recorded Journeys

0 / 15 points

Complete count_journeys(path): read the CSV at path and return its number of data rows as an integer. The file has mode and minutes columns. Its header and blank lines are not journeys.

A file with three data rows returns 3. A file containing only the header returns 0.

Check Your Understanding

  1. head() shows five rows. How would you check whether more observations are present without changing the table?
  2. How would you check that the duration column was read as numbers rather than text before calculating with it?
  3. The CSV gains a location column without adding or removing sessions. After reading the updated file, which parts of sessions.shape and sessions.columns should change, and which should stay the same? Explain how these results describe the observations and their fields.