Sheet 3 Numpy
Sheet 3 Numpy
2 7 12 0
3 9 3 4
4 0 1 3
>>> a
[ 3, 9, 3, 4],
[ 4, 0, 1, 3]])
>>> a.shape
(3, 4)
>>> a.ndim
>>> len(a)
Q) Can you get the ndim and len from the shape?
True
>>> np.arange(2, 6)
array([2, 3, 4, 5])
4. , 4.333333, 4.666667, 5. ])
>>> np.eye(6)
0 2 0
0 0 3
array([[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])
6. Make a shape (3, 5) array with random numbers from a standard normal
distribution (a normal distribution with mean 0 and variance 1).
>>> rand_arr.shape
(3, 5)
7. Make an array x with 100 evenly spaced values between 0 and 2 * pi;
>>> x.shape
(100,)
>>> y = np.cos(x)
>>> y.shape
(100,)
Plot x against y;
[...]
>>> rand_arr.shape
(10, 20)
>>> plt.imshow(rand_arr)
11. Investigate plt.cm. See if you can work out how to make the displayed
image be grayscale instead of color.
12. Create the following array, call this a (you did this before):
2 7 12 0
3 9 3 4
4 0 1 3
>>> a[1]
array([3, 9, 3, 4])
Get the 3rd column of a ([12 3 1]);
>>> a[:, 2]
array([12, 3, 1])
[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 2],
[1, 6, 1, 1]]
>>> arr1[3, 1] = 6
>>> arr1[2, 3] = 2
>>> arr1
array([[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 2],
[1, 6, 1, 1]])
[[4, 3, 4, 3, 4, 3],
[2, 1, 2, 1, 2, 1],
[4, 3, 4, 3, 4, 3],
[2, 1, 2, 1, 2, 1]]
array([[4, 3, 4, 3, 4, 3],
[2, 1, 2, 1, 2, 1],
[4, 3, 4, 3, 4, 3],
[2, 1, 2, 1, 2, 1]])
Fancy indexing using boolean arrays
1. Create the following array a (same as before):
2 7 12 0
3 9 3 4
4 0 1 3
2. Use > to make a mask that is true where the elements are greater than 5, like
this:
>>> mask
>>> a[mask]
>>> a[mask] = 5
>>> a
array([[2, 5, 5, 0],
[3, 5, 3, 4],
[4, 0, 1, 3]])
Elementwise operations
2 7 12 0
3 9 3 4
4 0 1 3
1. Use array slicing to get a new array composed of the even columns (0, 2) of a.
Now get array that contains the odd columns (1, 3) of a. Add these two arrays.
array([[ 9, 12],
[12, 7],
[ 4, 4]])
>>> 2 ** np.arange(5)
array([ 1, 2, 4, 8, 16])
x[i] = 2 ** (3 * i) - i
>>> x
Summary functions
2 7 12 0
3 9 3 4
4 0 1 3
>>> a.sum()
48
>>> a.sum(axis=0) # Sum over the first axis, leaving the second
>>> a.sum(axis=1) # Sum over the second axis, leaving the first
array([21, 19, 8])
mean?
>>> a.mean()
4.0
min?
>>> a.min()
max?
>>> a.max()