TExcelTAD
Home › Data Science › DS Functions

DS Functions

A few summary functions answer a surprising number of questions: What is the largest value? The smallest? The typical one? In this lesson you'll use them on plain Python lists, NumPy arrays and pandas columns, and write your own.

We use the first ten days of Riverside Bikes data:

day 1 2 3 4 5 6 7 8 9 10
temp_c 24.1 15.4 26.3 22.1 6.4 29.4 23.8 24.4 7.3 15.7
rides 414 298 439 405 254 523 497 428 209 368

Built-in Python functions

Python already has max(), min(), sum(), len() and sorted():

python · try it yourself
rides = [414, 298, 439, 405, 254, 523, 497, 428, 209, 368]

print("max:", max(rides))
print("min:", min(rides))
print("range:", max(rides) - min(rides))
print("mean:", sum(rides) / len(rides))
print("sorted:", sorted(rides))
max: 523
min: 209
range: 314
mean: 383.5
sorted: [209, 254, 298, 368, 405, 414, 428, 439, 497, 523]

The range (max − min) is the simplest measure of spread: rentals varied by 314 bikes between the quietest and busiest day.

NumPy functions

NumPy offers the same summaries plus many more, and they work on whole arrays — or on rows/columns of a 2-D array via axis:

python · try it yourself
import numpy as np

rides = np.array([414, 298, 439, 405, 254, 523, 497, 428, 209, 368])

print("mean:", np.mean(rides))
print("median:", np.median(rides))
print("std:", np.std(rides).round(2))
print("argmax (index of busiest day):", np.argmax(rides))
print("cumulative rides:", np.cumsum(rides))
mean: 383.5
median: 409.5
std: 96.73
argmax (index of busiest day): 5
cumulative rides: [ 414  712 1151 1556 1810 2333 2830 3258 3467 3835]

The median is the middle value after sorting (here the average of the 5th and 6th values). It is less affected by unusually high or low days than the mean.

pandas column methods

A pandas column (a Series) has all of these as methods, and describe() prints the most important ones at once:

python · try it yourself
import pandas as pd

days = pd.DataFrame({
    "temp_c": [24.1, 15.4, 26.3, 22.1, 6.4, 29.4, 23.8, 24.4, 7.3, 15.7],
    "rides":  [414, 298, 439, 405, 254, 523, 497, 428, 209, 368],
})

print("max rides:", days["rides"].max())
print("mean temp:", days["temp_c"].mean().round(2))
print()
print(days.max())
print()
print(days.describe().round(1))
max rides: 523
mean temp: 19.49

temp_c     29.4
rides     523.0
dtype: float64

       temp_c  rides
count    10.0   10.0
mean     19.5  383.5
std       7.9  102.0
min       6.4  209.0
25%      15.5  315.5
50%      23.0  409.5
75%      24.3  436.2
max      29.4  523.0

Calling a method on the whole DataFrame (days.max()) applies it to every column and returns one result per column.

Writing your own functions

When no built-in does what you need, write a function and apply it. Suppose the manager defines a busy day as one with more than 400 rides, and wants the share of busy days:

python · try it yourself
import pandas as pd

rides = pd.Series([414, 298, 439, 405, 254, 523, 497, 428, 209, 368])

def share_above(values, threshold):
    """Fraction of values strictly above threshold."""
    return (values > threshold).mean()

print("Share of busy days:", share_above(rides, 400))

def label(n):
    return "busy" if n > 400 else "normal"

print(rides.apply(label).value_counts())
Share of busy days: 0.6
busy      6
normal    4
Name: count, dtype: int64

Series.apply(f) calls f on every value. For simple conditions a vectorised expression like values > threshold is faster and shorter; use apply for logic that is hard to vectorise.

Summary

Question Function
Largest / smallest max(), min()
Typical value mean(), median()
Total / count sum(), len() / count()
Spread range, std() (see Standard Deviation)
Everything at once describe()
Custom rule your own def + apply()

Test yourself

What is the range of [5, 12, 7, 20]?

  1. 11
  2. 15
  3. 20
  4. 44

What does days.max() return when days is a DataFrame with two numeric columns?

  1. The single largest value in the table
  2. The largest value of each column
  3. The last row
  4. An error

Why can the median be a better "typical value" than the mean?

  1. It is always larger
  2. It is less affected by extreme values
  3. It is faster to compute
  4. It ignores missing values