Performant Python

Review of Numpy

Overview:

  • Teaching: 5 min
  • Exercises: 15 min

Questions

  • What is numpy?
  • How do I create and manipulate arrays with numpy?

Objectives

  • Know that numpy provides array structures to help improve your code.
  • Understand that numpy contains a rich range of library to create and manipulate arrays.

Numpy Arrays

  • Standard Python Library provides lists and 1d arrays (array.array)

    • Lists are general containers for objects
    • Arrays are 1d containers for objects of the same type
    • Limited functionality
    • Some memory and performance overhead associated with these structures
  • NumPy provides multidimensional arrays (numpy.ndarray)

    • Can store many elements of the same data type in multiple dimensions
    • cf. Fortran/C/C++ arrays
    • More functionality than core Python e.g. many conveninent methods for array manipulation
    • Efficient storage and execution

See, e.g.,

Creating Arrays (by hand)

We can create numpy arrays by hand, taking a list and and creating a numpy array from it:

In [1]:
import numpy as np
In [2]:
a = np.array( [-1, 0, 1] )
b = np.array( a )
print(a)
print(b)
[-1  0  1]
[-1  0  1]

All NumPy arrays are of type, ndarray

In [3]:
type(b)
Out[3]:
numpy.ndarray

Creating arrays (helper functions)

However often we want to create large array, that follow a specific sequence or of initial conditions:

Create Arrays

What arrays do the following do:

w = np.arange( -2, 6, 2 )
x = np.linspace(-10, 10, 5) 
y = np.zeros(3)
z = np.ones(3)

Solution

Attributes of Arrays

Every numpy array has attributes that describe e.g. its dimension and shape

In [8]:
print("Dimensions ", x.ndim)
Dimensions  1
In [9]:
print("Shape      ", x.shape)
Shape       (5,)

What are the following attributes:

x.size
x.dtype

What other attributes can you find for a numpy array (and how)?

Solution

Multi-dimensional arrays

Many different ways to create N-dimensional arrays. A two-dimensional array or matrix can be created from, e.g., list of lists

In [12]:
mat = np.array( [[1,2,3], [4,5,6]] )
print(mat)
print("Dimensions: ", mat.ndim)
print("Size:       ", mat.size)
print("Shape:      ", mat.shape)
[[1 2 3]
 [4 5 6]]
Dimensions:  2
Size:        6
Shape:       (2, 3)
In [13]:
mat0 = np.zeros( (3,3) )
print(mat0)
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
In [14]:
mat1 = np.ones( (3,3) )
print(mat0)
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

Key Points:

  • Numpy allows you to quickly create (multidimensional) arrays and popultate them
  • Numpy array attributes describe the array