import numpy as np
my_array = np.arange(10)
print('my_array -',my_array)
# get values between index 2 (included) and 6 (excluded)
print('my_array[2:6] -',my_array[2:6])
# get values between index 4 (included) the end of the array
print('my_array[4:] -',my_array[4:])
# get values between the start of the array and index 7 (excluded)
print('my_array[:7] -',my_array[:7])
my_array - [0 1 2 3 4 5 6 7 8 9] my_array[2:6] - [2 3 4 5] my_array[4:] - [4 5 6 7 8 9] my_array[:7] - [0 1 2 3 4 5 6]
Slicing with the form a:b:c, accesses indices between a and b, and indices that are multiples of c. For example:
print('my_array[2:9:2] -',my_array[2:9:2])
my_array[2:9:2] - [2 4 6 8]
# 4 by 4 array of zeros
print(np.zeros((4,4)))
[[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]]
# 6 by 3 array of ones
print(np.ones((6,3)))
[[1. 1. 1.] [1. 1. 1.] [1. 1. 1.] [1. 1. 1.] [1. 1. 1.] [1. 1. 1.]]
# 2 by 10 array of random numbers
print(np.random.rand(2,10))
[[0.61405163 0.52663249 0.59655916 0.17697362 0.00868107 0.65319468 0.43577846 0.70738606 0.52549845 0.83168464] [0.61957144 0.20098962 0.20853004 0.75346162 0.22582097 0.64537208 0.51449318 0.7450675 0.31139278 0.38297449]]
Note that the when specifying the shape of the array, the first argument is the number of rows and the second argument is columns.
You can get the shape of an array:
x = np.ones((6,3))
print(x.shape)
(6, 3)
Accessing elements in 2D arrays is done by separating the indices with a comma. The element in the second row, third column of an array would be accessed with the slice [1,2].
a = np.random.rand(3,3)
print(a)
print('second row, third column:',a[1,2])
[[0.02001174 0.03948266 0.74952907] [0.73733734 0.28709885 0.98744824] [0.33292761 0.6943921 0.33486185]] second row, third column: 0.9874482372627739
This applies when slicing as well, so getting all columns of the second row would be: [1,:]
a = np.random.rand(3,3)
print(a)
print('second row, all columns:',a[1,:])
[[0.17902056 0.31581658 0.29322188] [0.92680429 0.67945011 0.48351428] [0.54745637 0.11393077 0.54413224]] second row, all columns: [0.92680429 0.67945011 0.48351428]
You can also access the values in an array that meet certain conditions:
print(a[a > 0.5])
[0.92680429 0.67945011 0.54745637 0.54413224]
print(a[np.logical_and(a > 0.5, a < 0.8)])
[0.67945011 0.54745637 0.54413224]
Create a 5 by 5 array of random numbers between 0 and 10.