DCubes
Python module

Lesson 10

NumPy basics

ndarrays, shape, dtype, and vectorized operations — the array mental model under pandas and ML.

beginner35 minRun on your machine

What you will be able to do

  • Create a NumPy ndarray and read shape and dtype
  • Index and slice arrays
  • Apply element-wise arithmetic without Python for-loops

Why this matters for data work

NumPy is the in-memory array layer under pandas and most Python ML stacks. You may write pandas daily and NumPy weekly — but shape, dtype, and vectorization show up the moment performance or models matter.

Concepts

ndarray — N-dimensional array with a single dtype (e.g. float64, int64).

shape — dimensions, like (3,) or (2, 3).

Vectorization — operate on whole arrays: a * 2 instead of looping.

Broadcasting — NumPy aligns shapes for arithmetic when dimensions are compatible.

Practice on your machine

cd ~/dcubes/python-lab
source .venv/bin/activate
python -m pip install numpy
cat > numpy_lab.py << 'EOF'
import numpy as np

quantities = np.array([2, 1, 4], dtype=np.int64)
prices = np.array([9.99, 15.0, 9.99], dtype=np.float64)

print("quantities", quantities, quantities.shape, quantities.dtype)
line_totals = quantities * prices
print("line_totals", line_totals)
print("sum", float(line_totals.sum()))

matrix = np.array([[1.0, 2.0], [3.0, 4.0]])
print("matrix shape", matrix.shape)
print("first row", matrix[0])
print("cell", matrix[1, 1])
EOF
python numpy_lab.py
quantities [2 1 4] (3,) int64
line_totals [19.98 15.    39.96]
sum 74.94
matrix shape (2, 2)
first row [1. 2.]
cell 4.0

What you should see

  • 1-D arrays with shape (3,).
  • Element-wise multiply and a scalar sum.
  • 2-D indexing with [row, col].

Common mistakes

  • Python lists when you needed arrays — * repeats lists; it does not multiply element-wise.
  • Silent dtype upgrades — mixing int and float yields float arrays.
  • Assuming 1-D vs column vector — shape (3,) is not (3, 1).

Next

DataFrames