DS Database Table
Most organisations keep their data in tables: in a spreadsheet, in a CSV export, or in a relational database. A data scientist has to read these tables fluently — which parts they consist of, and how several tables relate to each other.
Anatomy of a table
Here is a slice of Riverside Bikes' daily log:
| date | temp_c | rain_mm | weekend | rides |
|---|---|---|---|---|
| 2024-04-01 | 24.1 | 0.0 | 0 | 414 |
| 2024-04-02 | 15.4 | 0.0 | 0 | 298 |
| 2024-04-06 | 29.4 | 0.0 | 1 | 523 |
| 2024-04-09 | 7.3 | 2.4 | 0 | 209 |
| Term | Meaning here |
|---|---|
| Column (field, variable, feature) | One measured property, e.g. temp_c |
| Row (record, observation) | One day |
| Cell | One value: the temperature on one day |
| Header | The column names |
| Key | A column that identifies each row uniquely — here date |
The shape of a table is rows × columns. The table above is 4 × 5.
Tables in Python
In plain Python a table can be stored as a list of rows. It works, but every calculation needs a loop:
header = ["date", "temp_c", "rain_mm", "weekend", "rides"]
rows = [
["2024-04-01", 24.1, 0.0, 0, 414],
["2024-04-02", 15.4, 0.0, 0, 298],
["2024-04-06", 29.4, 0.0, 1, 523],
["2024-04-09", 7.3, 2.4, 0, 209],
]
print("Shape:", len(rows), "x", len(header))
rides_col = header.index("rides")
print("Rides column:", [r[rides_col] for r in rows])
print("Weekend rows:", [r[0] for r in rows if r[header.index("weekend")] == 1])Shape: 4 x 5
Rides column: [414, 298, 523, 209]
Weekend rows: ['2024-04-06']
pandas gives the same table column labels, an index and fast column operations — the subject of the Data Frame lesson.
Several tables and keys
A database rarely holds everything in one table. Riverside Bikes keeps stations and trips separately, linked by a key:
stations.station_idis the primary key — unique for each station.trips.station_idis a foreign key — it points to a row instations.
Splitting avoids repeating the station's name and capacity on every trip, and a join puts the pieces back together when you need them. The playground below builds a tiny SQLite database in memory and loads a joined query straight into pandas:
import sqlite3
import pandas as pd
con = sqlite3.connect(":memory:")
con.executescript("""
CREATE TABLE stations (station_id INTEGER PRIMARY KEY, name TEXT, docks INTEGER);
INSERT INTO stations VALUES (1, 'Old Bridge', 20), (2, 'Market Sq', 15), (3, 'Riverside Park', 25);
CREATE TABLE trips (trip_id INTEGER PRIMARY KEY, station_id INTEGER, minutes INTEGER);
INSERT INTO trips VALUES (1, 1, 14), (2, 2, 32), (3, 1, 9), (4, 3, 21), (5, 1, 17), (6, 3, 40);
""")
query = """
SELECT s.name, COUNT(*) AS trips, AVG(t.minutes) AS avg_minutes
FROM trips t JOIN stations s ON s.station_id = t.station_id
GROUP BY s.name
ORDER BY trips DESC
"""
print(pd.read_sql_query(query, con)) name trips avg_minutes
0 Old Bridge 3 13.333333
1 Riverside Park 2 30.500000
2 Market Sq 1 32.000000
Note: You don't need to master SQL for this course — the SQL course on this site covers it. What matters is recognising keys and knowing that joining tables is how separate facts come together.
Wide versus long tables
The same data can be laid out in two ways:
- Wide: one row per day, one column per station.
- Long (tidy): one row per day + station combination, with a single
ridescolumn.
Most analysis tools prefer the long, tidy form: every variable is a column, every observation a row, every value a cell. pandas converts between them with melt (wide → long) and pivot (long → wide):
import pandas as pd
wide = pd.DataFrame({
"date": ["2024-04-01", "2024-04-02"],
"Old Bridge": [150, 112],
"Market Sq": [139, 98],
})
long = wide.melt(id_vars="date", var_name="station", value_name="rides")
print(long)
print()
print(long.pivot(index="date", columns="station", values="rides")) date station rides
0 2024-04-01 Old Bridge 150
1 2024-04-02 Old Bridge 112
2 2024-04-01 Market Sq 139
3 2024-04-02 Market Sq 98
station Market Sq Old Bridge
date
2024-04-01 139 150
2024-04-02 98 112
Test yourself
What is the shape of a table with 60 daily records and 6 columns?
- 6 × 60
- 60 × 6
- 360
- 66
In trips, the column station_id that refers to stations.station_id is called a…
- Primary key
- Foreign key
- Header
- Index label
Which layout is "tidy"?
- One column per station, one row per day
- One row per day + station, with a single
ridescolumn - One cell holding a list of all rides
- Each day in a separate table