🎓 A1Learner
🔍
0 of 50 lessons completed

Python ML NumPy Arrays for Machine Learning

A NumPy array is a grid of numbers that Python can work on all at once. One line of code can add, multiply, or compare every number in the grid.

A list becomes an array

np.array turns a list into an array. The shape (4,) means four numbers in one row.

import numpy as np
a = np.array([1, 2, 3, 4])
print(a)
print(a.shape)

Rows and columns have addresses

The grid holds 2 rows and 3 columns. The first row is 1, 2, 3, and the middle column is 2, 5.

import numpy as np
grid = np.array([[1, 2, 3], [4, 5, 6]])
print(grid.shape)
print(grid[0])
print(grid[:, 1])

One line changes every number

Multiplying by 2 doubles every number at once. Adding 10 adds 10 to each one.

import numpy as np
a = np.array([1, 2, 3])
print(a * 2)
print(a + 10)

A dot product is one number

Pairs multiply and the results add up. The total is 32.

import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.dot(a, b))

Example

import numpy as np
marks = np.array([[80, 90, 70], [60, 75, 85], [95, 85, 90]])
print("Shape:", marks.shape)
print("First student:", marks[0])
print("Mean marks:", marks.mean(axis=1).round(1))
print("Mean per test:", marks.mean(axis=0).round(1))
print("Total:", marks.sum())

Key points

  • Array: a grid of numbers held in one NumPy object
  • Shape: the size of the array, written as rows and columns, like (2, 3)
  • Axis: the direction a job runs in. Axis 0 works down each column, and axis 1 works across each row.
  • Use np.array() to turn a list into an array
  • Use array.shape to read the size of an array
  • Slicing picks rows or columns out of an array, like grid[0] for the first row
  • A dot product multiplies two lists of numbers pair by pair and adds the results

In this example, the array holds three students and three marks each. The shape (3, 3) says three rows and three columns. Mean along axis 1 gives one mean per student. Mean along axis 0 gives one mean per test. The total of all nine marks is 730. One array holds the whole table, and one line works on every number in it.

Note

An array holds one kind of number only. Mixing text and numbers in one array causes trouble.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What is the shape of np.array([[1, 2, 3], [4, 5, 6]])?