TExcelTAD
Home › Data Science › DS Data Frame

DS Data Frame

A DataFrame is pandas' table: labelled columns, a row index, and one NumPy array behind each column. It is the object you'll work with in almost every lesson from now on.

The Riverside Bikes dataset

So far we used ten hand-typed days. From here on we use the full dataset: 60 days (1 April – 30 May 2024) of rentals. Because the playgrounds can't download files, every example builds the table with the same short block of code. It uses a seeded random generator, so the "random" weather and rentals are identical in every lesson and on every computer.

python · try it yourself
import numpy as np
import pandas as pd

# Riverside Bikes: 60 days of rentals (the same builder is used throughout the course)
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

print(bikes.head())
print("Shape:", bikes.shape)
        date  temp_c  rain_mm  humidity  weekend  rides
0 2024-04-01    24.1      0.0        85        0    414
1 2024-04-02    15.4      0.0        88        0    298
2 2024-04-03    26.3      0.0        48        0    439
3 2024-04-04    22.1      0.0        88        0    405
4 2024-04-05     6.4      0.0        41        0    254
Shape: (60, 6)

The columns are:

Column Meaning
date Calendar day
temp_c Average daytime temperature (°C)
rain_mm Rainfall (mm); 0.0 on dry days
humidity Relative humidity (%)
weekend 1 on Saturday/Sunday, else 0
rides Number of bike rentals that day — the value we want to explain

Note: The rentals were simulated from a rule (more rides when warm, fewer when wet, more at weekends, plus noise). That's useful for learning: later you can check whether regression recovers the rule.

Inspecting a DataFrame

The first thing to do with any new table is look at its structure:

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

print(bikes.dtypes)
print()
print(bikes.columns.tolist())
print(bikes.tail(3))
date        datetime64[ns]
temp_c             float64
rain_mm            float64
humidity             int64
weekend              int32
rides                int32
dtype: object

['date', 'temp_c', 'rain_mm', 'humidity', 'weekend', 'rides']
         date  temp_c  rain_mm  humidity  weekend  rides
57 2024-05-28    18.8      0.0        42        0    359
58 2024-05-29     7.6      0.0        52        0    255
59 2024-05-30     7.0      0.0        65        0    264
Attribute / method Shows
df.shape (rows, columns)
df.dtypes Type of each column
df.columns Column labels
df.head(n) / df.tail(n) First / last n rows
df.info() Types, non-null counts and memory in one report
df.describe() Summary statistics

Selecting columns and rows

  • df["col"] → one column (a Series); df[["a", "b"]] → several columns (a DataFrame).
  • df.loc[rows, cols] → select by label.
  • df.iloc[rows, cols] → select by position.
  • df[condition] → keep rows where a boolean condition is True.
python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

print(bikes.loc[0:2, ["date", "rides"]])
print(bikes.iloc[-1, 1:3])
print()
wet_weekends = bikes[(bikes["rain_mm"] > 0) & (bikes["weekend"] == 1)]
print(wet_weekends[["date", "rain_mm", "rides"]])
        date  rides
0 2024-04-01    414
1 2024-04-02    298
2 2024-04-03    439
temp_c     7.0
rain_mm    0.0
Name: 59, dtype: object

         date  rain_mm  rides
13 2024-04-14      5.9    447
47 2024-05-18     12.3    220
48 2024-05-19      5.4    420
54 2024-05-25      3.3    444

Combine conditions with & (and), | (or) and ~ (not), and put each condition in parentheses.

Adding columns and sorting

New columns are computed from existing ones in a single vectorised line. sort_values orders the rows:

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

bikes["temp_f"] = (bikes["temp_c"] * 9 / 5 + 32).round(1)
bikes["wet"] = bikes["rain_mm"] > 0
top = bikes.sort_values("rides", ascending=False).head(5)
print(top[["date", "temp_c", "wet", "rides"]])
print()
print("Wet days:", bikes["wet"].sum(), "of", len(bikes))
         date  temp_c    wet  rides
41 2024-05-12    25.6  False    572
20 2024-04-21    23.7  False    570
11 2024-04-12    28.1  False    527
5  2024-04-06    29.4  False    523
6  2024-04-07    23.8  False    497

Wet days: 18 of 60

The five busiest days are all warm and dry, and most fall on a weekend — the first clues for the analysis to come.

Test yourself

What does bikes[["temp_c", "rides"]] return?

  1. A Series
  2. A DataFrame with two columns
  3. A tuple of two Series
  4. An error

Which selects rows by **position** rather than by label?

  1. df.loc
  2. df.iloc
  3. df.at
  4. df["col"]

How do you keep rows that are dry **and** on a weekend?

  1. df[df.rain_mm == 0 and df.weekend == 1]
  2. df[(df.rain_mm == 0) & (df.weekend == 1)]
  3. df[df.rain_mm == 0, df.weekend == 1]
  4. df.where(rain_mm=0, weekend=1)