Python I Flashcards
attribute for getting the dimensions of a numpy array (e. g. (3, 4, 2))
arr.shape
attribute for getting the datatype of a numpy array
arr.dtype
attribute for getting the number of dimensions of a numpy array
arr.ndim
attribute for getting the number of all elements of a numpy array
arr.size
creating an array in numpy
np.array(my_list)
creating a range in numpy
np.arange(start, stop, step)
creating ranges of values in numpy
np.linspace(start, stop, numberOfElems, endpoint=True/False)
get multiple elements of a numpy array (index)
one_dim[[3, 4, 6, 15]] (gets elements at index 3, 4, 5, 6 and 15)
get the element of the 3rd row and 4th column of a numpy array
arr[2, 3] or arr[(2, 3)]
get the second row of a multidimensional numpy array
arr[1]
get the second column of a multidimensional numpy array
arr[: , 1]
extract the bottom right 2x2 corner of a 3x4 numpy array
arr[1:3, 2:4]
indexing of numpy arrays is also possible via masks
mask = np.array([[True, False, False, True],
[False, True, False, True],
[False, False, True, True]])
print(“two_dim[mask]”)
print(two_dim[mask])
(Returns flat (1D) array of elements where mask = True)
only extract even number out of a numpy array
mask = (arr % 2) == 0
print(arr[mask])
additional information numpy arrays
x2 = two_dim[:][2]
This will first create a slice of the array (in this case, this is simply the entire array again) and then access index 2 in that sliced array, which corresponds to “two_dim[2]”
additional information numpy arrays
x2 = two_dim[:][2]
This will first create a slice of the array (in this case, this is simply the entire array again) and then access index 2 in that sliced array, which corresponds to “two_dim[2]”
additional information numpy arrays
x2 = two_dim[:][2]
This will first create a slice of the array (in this case, this is simply the entire array again) and then access index 2 in that sliced array, which corresponds to “two_dim[2]”
additional information numpy arrays
x2 = two_dim[:][2]
This will first create a slice of the array (in this case, this is simply the entire array again) and then access index 2 in that sliced array, which corresponds to “two_dim[2]”
set all elements from index 2 to 4 to zero in a numpy array
one_dim[2:5] = [0, 0, 0]
or
one_dim[2:5] = 0 (broadcasting)
set all entries of a twodimensional numpy array to 0
two_dim[:] = 0
set the second to third element of the second row of a numpy array to 0
two_dim[1, 1:4] = 0
(also subarrays can be broadcasted, e. g.
two_dim[:, 1:3] = [7, 8])
When can numpy arrays be reshaped?
When the number of elements stays the same.
a = np.arange(24)
a = a.reshape(2, 3, 4)
a = a.reshape(4, 6)
a = a.reshape(6, -1)
add an empty dimension
a1 = a[:, None, :]
a2 = a[:, np.newaxis, :]
Other important numpy functions
print(np.append(a, np.array([1, 2, 3])))
print(np.concatenate([a, a, a]))
print(np.repeat(a, repeats=5))
print(np.tile(a, reps=5))