This tutorial introduces numpy, a Python library for performing numerical computations in Python.
import
. Also, to avoid typing numpy
every time we want to use one if its functions we can provide an alias using the special word as
:¶import numpy as np
numpy
by typing np.name_of_function
. For example, the equivalent of 1 + 1
in Python can be done in numpy
:¶np.add(1,1)
numpy
than in standard Python when using lots of numbers.¶Tip: To access the documentation explaining how a function is used, its input parameters and output format we can press
Shift+Tab
after the function name"
np.add
a = np.add(2,3)
a
that holds the result of the function. We cannow use of display this variable, at any point of this notebook. For example we can show its contents by typing the variable name in a new cell:¶a
34
and 29
¶from check_answer import check_answer
# Substitute the ? symbols by the correct expressions and values
answ = ?
check_answer("1.1", answ)
array
, which is equivalent to numpy lists, but can be multidimensional and with much more functionality. To declare a numpy array explicity we do:¶np.array([1,2,3,4,5,6,7,8,9])
add
operation:¶arr1 = np.array([1,2,3,4])
arr2 = np.array([3,4,5,6])
np.add(arr1, arr2)
Note: This operation detects that numpy arrays are being added and calls the previous function for efficient execution. Think that these arrays can contain large amounts of values.
arr1 + arr2
[start:end:stride]
. Let's see what this means:¶arr = np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])
print(arr[5])
print(arr[5:])
print(arr[:5])
print(arr[::2])
0
, the same convention used in Python lists.¶# Substitute the ? symbols by the correct expressions and values
arr = ?
answ = arr[?:?]
check_answer("1.2", answ)
arr = np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])
arr[-2:]
# Substitute the ? symbols by the correct expressions and values
answ = arr[?]
check_answer("1.3", answ)
Tip: Result should be ?
[0,3,6,9,12]
answ = arr[?:?:?]
check_answer("1.4", answ)
(1,9)
array using nested square brackets [ ]. The convention in numpy is that the outer [ ] represent the first dimension and the inner [ ] contains the last dimension.¶np.array([[1,2,3,4,5,6,7,8,9]])
.shape
to an array expression or variable containing a numpy array.¶arr1 = np.array([1,2,3,4,5,6,7,8,9])
arr2 = np.array([[1,2,3,4,5,6,7,8,9]])
arr3 = np.array([[1],[2],[3],[4],[5],[6],[7],[8],[9]])
arr1.shape, arr2.shape, arr3.shape, np.array([1,2,3]).shape
reshape
:¶Note: The total number of elements has to be the same before and after the reshape operation, otherwise numpy will throw and error.
np.array([1,2,3,4,5,6,7,8]).reshape((2,4))
Note: We are declaring the array and reshaping all in one line. This is called 'chaining' and allows us to conveniently perform multiple operations. The expressions are evaluated from left to right, so in this case first we create and array and then apply the reshape operation to the resulting array.
arr1 = np.array([1,2,3,4,5,6,7,8,9]).reshape(1,9)
arr2 = np.array([1,2,3,4,5,6,7,8,9]).reshape(9,1)
arr3 = np.array([1,2,3,4,5,6,7,8,9]).reshape(3,3)
arr1.shape, arr2.shape, arr3.shape
# variable answ should contain your 2-dimensional array with shape (2,3)
answ = ?
check_answer("1.5", answ.shape)
arr1 = np.arange(9)
arr2 = np.ones((3,3))
arr3 = np.zeros((2,2,2))
print(arr1)
print("--------")
print(arr2)
print("--------")
print(arr3)
# variable answ should contain your 3-dimensional array with shape (5,3,3)
answ = ?
check_answer("1.6", answ.shape)
arr1 = ?
arr2 = ?
answ = np.?
check_answer("1.7", answ.shape)
arr = np.arange(9).reshape((3,3))
print(arr)
print("--------")
print("Mean:", np.mean(arr))
print("Std Dev:", np.std(arr))
print("Sum:",np.sum(arr))
arr = np.arange(9).reshape((3,3))
print(arr)
print("--------")
print("Sum along the vertical axis:", np.sum(arr, axis=0))
print("--------")
print("Sum along the horizontal axis:", np.sum(arr, axis=1))
# variable answ should contain your 3-dimensional array with shape (5,3,3)
answ = ?
check_answer("1.8", answ)
Integers
uint8
uint16
uint32
uint64
int8
int16
int32
int64
Floats
float32
float64
.dtype
suffix.¶arr = np.ones((10,10,10))
arr.dtype
dtype
parameter to the declaration expression.¶arr = np.ones((10,10,10), dtype=np.uint8)
arr.dtype
.astype
function.¶arr = np.ones((10,10,10))
arr = arr.astype(np.float32)
# Or all in one line
arr = np.ones((10,10,10)).astype(np.float32)
arr.dtype
int16
¶answ = np.arange(10)
answ = answ#Your code goes here
check_answer("1.9", answ.dtype)
a = np.zeros((10,10))
a = a + 1
a
a
and then we add 1
to this variable. However, 1
is a single value and is not even an array so it is not entirely clear what is going on. Broadcasting is the ability in numpy to arrays to replicate or promoted arrays involved in operations to match their shapes.¶a = np.arange(9).reshape((3,3))
b = np.arange(3)
a + b
2
values?¶Tip: We have just seen an example of broadcasting by adding a single value to an array. Broadcasting also works with other operations, such as multiplication or division, so you can complete this exercise declaring an initial array containing all zeros or ones and then using one operation to modify all its values.
answ = ?
check_answer("1.10", answ)
True
, False
]. For example:¶arr = np.array([True, False, True])
arr, arr.shape, arr.dtype
and
, or
and others.¶arr1 = np.array([True, True, False, False])
arr2 = np.array([True, False, True, False])
print(np.logical_and(arr1, arr2))
print(np.logical_or(arr1, arr2))
*
and +
.¶Note: Here the
*
and+
symbols are not performing multiplication and addition as with numerical arrays. Numpy detects the type of the arrays involved in the operation and changes the behaviour of these operators. This ability to change the behaviour of operators depending on the situation is called 'operator overloading' in programming languages.
print(arr1 * arr2)
print(arr1 + arr2)
arr = np.array([1, 3, 5, 1, 6, 3, 1, 5, 7, 1])
print(arr == 1)
print(arr > 2)
3
and less than 7
.¶arr = np.array([1, 3, 5, 1, 6, 3, 1, 5, 7, 1])
answ = ?
check_answer("1.11", answ)
arr = np.array([1,2,3,4,5,6,7,8,9])
mask = np.array([True,False,True,False,True,False,True,False,True])
arr[mask]
3
and less than 7
. In this case you want a new smaller array containing just the values that are within that range.¶arr = np.array([1, 3, 5, 1, 6, 3, 1, 5, 7, 1])
answ = ?
check_answer("1.12", answ)
a = np.array([0,0,0])
# We make a copy of array a with name b
b = a
# We modify the first element of b
b[0] = 1
print(a)
print(b)
b = np.copy(a)
function to explicitly make a copy of the array.¶a = np.array([0,0,0])
# We explicitly make a copy of array a with name b
b = np.copy(a)
# We modify the first element of b
b[0] = 1
print(a)
print(b)