TExcelTAD
Home › Data Science › DS & Python

DS & Python

Python is the most popular language for data science. The language itself is simple to read, but its real strength is the ecosystem: a stack of libraries that work together, each building on the one below.

Layer Library Role
Arrays NumPy Fast numeric arrays and vectorised maths
Tables pandas Labelled tables, cleaning, grouping, time series
Charts Matplotlib, seaborn Static plots; seaborn adds statistical charts
Science SciPy Statistics, optimisation, distributions
Models statsmodels, scikit-learn Regression with statistical detail; machine learning

You import them with short, conventional aliases. Everyone uses the same ones, so stick to them:

python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels.formula.api as smf

Why not just lists?

A Python list can hold anything, which makes it flexible but slow for maths: you must loop over items one at a time. A NumPy array holds values of one type in a compact block of memory, and operations apply to every element at once. This is called vectorisation.

python · try it yourself
import numpy as np

temps_c = [24.1, 15.4, 26.3, 22.1, 6.4]

# With a list you need a loop (or comprehension):
temps_f_list = [t * 9 / 5 + 32 for t in temps_c]
print(temps_f_list)

# With an array the formula applies to all elements at once:
arr = np.array(temps_c)
print(arr * 9 / 5 + 32)
print(type(arr), arr.dtype, arr.shape)
[75.38, 59.72, 79.34, 71.78, 43.519999999999996]
[75.38 59.72 79.34 71.78 43.52]
<class 'numpy.ndarray'> float64 (5,)

Array operations

Arithmetic between two arrays of the same length works element by element. Comparisons produce boolean arrays, which you can use to filter:

python · try it yourself
import numpy as np

temp = np.array([24.1, 15.4, 26.3, 22.1, 6.4, 29.4, 23.8])
rides = np.array([414, 298, 439, 405, 254, 523, 497])

print("Rides per degree:", (rides / temp).round(1))
warm = temp > 20
print("Warm day mask:", warm)
print("Rides on warm days:", rides[warm])
print("How many warm days:", warm.sum())
Rides per degree: [17.2 19.4 16.7 18.3 39.7 17.8 20.9]
Warm day mask: [ True False  True  True False  True  True]
Rides on warm days: [414 439 405 523 497]
How many warm days: 5

warm.sum() counts the True values, because True behaves like 1 and False like 0.

Useful NumPy helpers

Function Does
np.arange(start, stop, step) Evenly spaced values (like range)
np.linspace(a, b, n) n evenly spaced values from a to b inclusive
np.round(x, d) / x.round(d) Round to d decimals
np.where(cond, a, b) Pick a where cond is true, else b
rng = np.random.default_rng(seed) A reproducible random number generator

Reproducible randomness

Data scientists often simulate data to test an idea. Always create a generator with a fixed seed: then the "random" numbers are identical every time the code runs, and anyone can reproduce your result.

python · try it yourself
import numpy as np

rng = np.random.default_rng(42)
print(rng.integers(1, 7, size=10))     # ten dice rolls

rng = np.random.default_rng(42)        # same seed -> same numbers
print(rng.integers(1, 7, size=10))

print(np.linspace(0, 30, 7))
print(np.where(np.array([3, 0, 5]) > 0, "rain", "dry"))
[1 5 4 3 3 6 1 5 2 1]
[1 5 4 3 3 6 1 5 2 1]
[ 0.  5. 10. 15. 20. 25. 30.]
['rain' 'dry' 'rain']

Tip: Never rely on unseeded randomness in an analysis you share. "It worked on my machine" is not reproducible science.

From arrays to tables

NumPy arrays have no column names. As soon as you have several related variables — date, temperature, rain, rides — you want them in a pandas DataFrame, where each column is a NumPy array with a label:

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

temp = np.array([24.1, 15.4, 26.3])
rides = np.array([414, 298, 439])

df = pd.DataFrame({"temp_c": temp, "rides": rides})
df["rides_per_deg"] = (df["rides"] / df["temp_c"]).round(1)
print(df)
print(type(df["temp_c"].to_numpy()))
   temp_c  rides  rides_per_deg
0    24.1    414           17.2
1    15.4    298           19.4
2    26.3    439           16.7
<class 'numpy.ndarray'>

The next lessons build on exactly this: functions that summarise columns, and the DataFrame itself.

Test yourself

What is the conventional alias for pandas?

  1. import pandas as pa
  2. import pandas as pd
  3. import pandas as p
  4. from pandas import *

What does np.array([1, 2, 3]) * 2 return?

  1. [1, 2, 3, 1, 2, 3]
  2. array([2, 4, 6])
  3. An error
  4. 6

Why create np.random.default_rng(42) with a seed?

  1. It makes the numbers more random
  2. It makes results reproducible
  3. It is required by NumPy
  4. It makes code faster