numpy Basics
Ralph Tambala
1 The numpy Basics
NumPy's main object is the homogeneous multidimensional array. It is a table of elements (usually numbers),
all of the same type, indexed by a tuple of non-negative integers. In NumPy dimensions are called axes.
For example, the coordinates of a point in 3D space [1,2,1] has one axis. That axis has 3 elements in it, so we
say it has a length of 3. In the example pictured below, the array has 2 axes. The first axis has a length of 2, the
second axis has a length of 3.
In [ ]:
import numpy as np
ls = [[ 1, 0, 0], [ 0, 1, 2]]
arr = np.array(ls)
arr
NumPy's array class is called ndarray. It is also known by the alias array.
In [ ]:
type(arr)
In [ ]:
type(ls)
The more important properties of an ndarray object are: ndim, shape, size, dtype
ndarray.ndim: the number of axes (dimensions) of the array.
In [ ]:
arr1 = np.array([[[ 1, 0, 0], [ 0, 1, 2], [1, 1, 1]], [[ 1, 0, 0], [ 0, 1, 2], [1, 1, 1]]])
arr1.ndim
ndarray.shape: the dimensions of the array. This is a tuple of integers indicating the size of the array in
each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape
tuple is therefore the number of axes, ndim.
In [ ]:
arr = np.array([[1, 3, 4, 5 ], [1, 3, 4, 5 ], [1, 3, 4, 5 ]], dtype='float64')
arr.dtype
In [ ]:
arr
In [ ]:
arr.shape
ndarray.size: the total number of elements of the array. This is equal to the product of the elements of
shape.
In [ ]:
arr.size
ndarray.dtype: an object describing the type of the elements in the array. One can create or specify
dtype’s using standard Python types. Additionally NumPy provides types of its own. numpy.int32,
numpy.int16, and numpy.float64 are some examples.
In [ ]:
arr.dtype
2 Array Creation […]
3 Shape Manipulation
3.1 ndarray.ravel()
ndarray.ravel() returns the array flattened but does not modify the original shape.
In [ ]:
arr = np.random.random_sample((3,3))
arr
In [ ]:
arr.shape
In [ ]:
arr3 = arr.ravel()
arr3
In [ ]:
arr3.shape # still maintains original shape
3.2 reshape(shape)
ndarray.reshape(shape) method returns its argument with a modified shape:
In [ ]:
arr = np.ones((4, 4), dtype='int32')
arr
In [ ]:
arr4 = arr.reshape((2, 2, 2, 2))
arr4
In [ ]:
arr4.ndim
3.3 ndarray.resize(shape)
ndarray.resize(shape) method modifies the array itself:
In [ ]:
arr = np.zeros((2, 4), dtype='int32')
arr
In [ ]:
arr.resize((4,2))
In [ ]:
arr
4 Matrix Operations
4.1 scalar arithmetic
Any arithmetic operation between a scalar and a numpy array results into an array, same as in maths.
In [ ]:
arr = np.eye(3, dtype=int)
arr
In [ ]:
arr = arr * 2
arr
In [ ]:
arr = arr ** 3
arr
In [ ]:
arr + arr / 4 + 4
4.2 ndarray.T or ndarray.transpose()
ndarray.T returns the transposed array
In [ ]:
arr = np.array([[1, 2, 3], [4, 5, 6]])
arr
In [ ]:
arr.T
In [ ]:
arr.transpose()
4.3 dot product vs cross product vs element-wise product
In [ ]:
# dot product
p = np.array([1, 2, 3])
q = np.array([4, 5, 6])
np.dot(p, q)
In [ ]:
p.dot(q)
In [ ]:
p @ q # at symbol
In [ ]:
# cross product
np.cross(p, q)
In [ ]:
# element-wise product
p * q
5 Indexing with Boolean arrays and other tricks
In [ ]:
b = np.arange(12)**2
b
In [ ]:
a = np.arange(12)**2 # the first 12 square numbers
i = np.array( [1,1,3,8,5] ) # an array of indices
a[i]
In [ ]:
j = np.array( [[3, 4], [9, 1]] ) # a bidimensional array of indices
a[j] # the same shape as j
In [ ]:
a = np.arange(3, 100, 3).reshape((3,11)) # numbers divisible by 3 below 100
a
In [ ]:
a[:, 10]
In [ ]:
a[1:, 1:5]
In [ ]:
a > 50
In [ ]:
a[a > 50]
In [ ]:
a[a > 65]
In [ ]:
a = np.ones((5,5), int)
a
In [ ]:
a[:, 4] = 8 # change only last column to 8s
a
In [ ]:
a[:2, :3] = 0
a[3:, :3] = 0
a
6 Practice Work
1. Import the numpy package under the alias np.
In [ ]:
2. Write code to create an array similar to the matrices below:
a.
(1 2 3)
In [ ]:
# a
b.
1 2 3
(4 5 6)
In [ ]:
# b
1 1
c.
1 1
1 1 1 1
1 1 1 1
1 1 1 1
In [ ]:
# c
1 0
d.
0 0 0
0 1 0 0 0
00 0 1 0 0
0 0 1 0
0 0 0 0 1
In [ ]:
# d
e.
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
(2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
In [ ]:
# e
3. Create an identity matrix of dimension 100 by 100
In [ ]:
4. Create a 1-D array of even values from 2-2000000.
In [ ]:
5. Create a 1-D array of 200 values between 1 and 10.
In [ ]:
6. Create a 10 by 1000 matrix of counting values 1-10000. First row should have values 1, 2, ... 1000, second
should have values 1001, 102, ..., 2000 and so on up to 10th row should have values 9001, 9002, ...,
10000. Below is the visual representation of the forementioned matrix.
1 2 3 ... 999 1000
1001 1002 1003 ... 1999 2000
2001 2002 2003 ... 2999 3000
... ... ... ... ... ... ... ...
8001 8002 8003 ... 8999 9000
9001 9002 9003 ... 9999 10000
In [ ]:
7. Flatten the matrix in question 5.
In [ ]:
8. Reshape the flattened matrix in Question 6 to a 100 by 100 matrix.
In [ ]:
9. Extract all odd numbers from arr
In [ ]:
arr = np.array([12, 11, 7, 4, 19, 62, 71, 10, 81, 100])
# code here
Output: array([11, 7, 19, 71, 81])
10. Find out how each of the following numpy functions may be used and give an example for illustration of
usage:
a. np.full()
b. np.tile()
c. np.vstack()
d. np.hstack()
In [ ]: