Numpy Tutorial

# Install dependencies


import ds_tut
ds_tut.setup()
Note: you may need to restart the kernel to use updated packages.
import numpy as np

Builtin Help

It’s very easy to get additional help just from within a notebook.

? / help / ??

  • Just append a ? to an item to see the docstring or call help(item)
  • Append ?? to view the source
#np.array?
#help(np.array)
#np.abs??

How to find Functions

#np.lookfor('diagonal')

Indices

a = np.arange(9).reshape(3, 3)
print(a)
[[0 1 2]
 [3 4 5]
 [6 7 8]]
a[1:,1:]
array([[4, 5],
       [7, 8]])
a[::-1]
array([[6, 7, 8],
       [3, 4, 5],
       [0, 1, 2]])
a[a > 5] = 0
print(a)
[[0 1 2]
 [3 4 5]
 [0 0 0]]
a.ravel()[::2] = 1
print(a)
[[1 1 1]
 [3 1 5]
 [1 0 1]]

Broadcasting

a = np.arange(9).reshape(3, 3)
print(a * 10)
[[ 0 10 20]
 [30 40 50]
 [60 70 80]]
b = np.array((10, 10, 10))
print(b)
[10 10 10]
print(a + b)
[[10 11 12]
 [13 14 15]
 [16 17 18]]
print(a * b)
[[ 0 10 20]
 [30 40 50]
 [60 70 80]]

Non Scalar Multiplication

(b @ b) ** .5
17.320508075688775
a.dot(b), a @ b
(array([ 30, 120, 210]), array([ 30, 120, 210]))
a @ np.arange(9).reshape(3, 3)
array([[ 15,  18,  21],
       [ 42,  54,  66],
       [ 69,  90, 111]])
c = np.arange(4)
a @ c
ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 4 is different from 3)

Elementwise Comparison

a = np.full((2, 3), fill_value=2)
b = np.full((2, 3), fill_value=2)
a is b
False
a == b
array([[ True,  True,  True],
       [ True,  True,  True]])
np.all(a == b)
True
b[0, 0] = 1
np.all(a == b)
False

Performance

n = 1000000

Arrays vs Lists

from math import sqrt
long_list = list(range(n))
39.7 ms ± 668 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
long_array = np.arange(n)
879 µs ± 38.6 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)

Loops are Bad

x = 27
count = 0
for i in range(1000000):
    if i % x == 0:
        count += 1
UsageError: Line magic function `%%timeit` not found.
a = np.arange(n)
count = 0
for i in a:
    if i % x == 0:
        count += 1