23 KiB
23 KiB
In [ ]:
import numpy as np
rng = np.random.default_rng(seed=1701) # seed for reproducibility
x1 = rng.integers(10, size=6) # one-dimensional array
x2 = rng.integers(10, size=(3, 4)) # two-dimensional array
x3 = rng.integers(10, size=(3, 4, 5)) # three-dimensional arrayIn [ ]:
print("x3 ndim: ", x3.ndim)
print("x3 shape:", x3.shape)
print("x3 size: ", x3.size)
print("dtype: ", x3.dtype)In [ ]:
x1In [ ]:
x1[0]In [ ]:
x1[4]In [ ]:
x1[-1]In [ ]:
x1[-2]In [ ]:
x2In [ ]:
x2[0, 0]In [ ]:
x2[2, 0]In [ ]:
x2[2, -1]In [ ]:
x2[0, 0] = 12
x2In [ ]:
x1[0] = 3.14159 # this will be truncated!
x1In [ ]:
x1In [ ]:
x1[:3] # first three elementsIn [ ]:
x1[3:] # elements after index 3In [ ]:
x1[1:4] # middle subarrayIn [ ]:
x1[::2] # every second elementIn [ ]:
x1[1::2] # every second element, starting at index 1In [ ]:
x1[::-1] # all elements, reversedIn [ ]:
x1[4::-2] # every second element from index 4, reversedIn [ ]:
x2In [ ]:
x2[:2, :3] # first two rows & three columnsIn [ ]:
x2[:3, ::2] # three rows, every second columnIn [ ]:
x2[::-1, ::-1] # all rows & columns, reversedIn [ ]:
x2[:, 0] # first column of x2In [ ]:
x2[0, :] # first row of x2In [ ]:
x2[0] # equivalent to x2[0, :]In [ ]:
print(x2)In [ ]:
x2_sub = x2[:2, :2]
print(x2_sub)In [ ]:
x2_sub[0, 0] = 99
print(x2_sub)In [ ]:
print(x2)In [ ]:
x2_sub_copy = x2[:2, :2].copy()
print(x2_sub_copy)In [ ]:
x2_sub_copy[0, 0] = 42
print(x2_sub_copy)In [ ]:
print(x2)In [ ]:
grid = np.arange(1, 10).reshape(3, 3)
print(grid)In [ ]:
x = np.array([1, 2, 3])
x.reshape((1, 3)) # row vector via reshapeIn [ ]:
x.reshape((3, 1)) # column vector via reshapeIn [ ]:
x[np.newaxis, :] # row vector via newaxisIn [ ]:
x[:, np.newaxis] # column vector via newaxisIn [ ]:
x = np.array([1, 2, 3])
y = np.array([3, 2, 1])
np.concatenate([x, y])In [ ]:
z = np.array([99, 99, 99])
print(np.concatenate([x, y, z]))In [ ]:
grid = np.array([[1, 2, 3],
[4, 5, 6]])In [ ]:
# concatenate along the first axis
np.concatenate([grid, grid])In [ ]:
# concatenate along the second axis (zero-indexed)
np.concatenate([grid, grid], axis=1)In [ ]:
# vertically stack the arrays
np.vstack([x, grid])In [ ]:
# horizontally stack the arrays
y = np.array([[99],
[99]])
np.hstack([grid, y])In [ ]:
x = [1, 2, 3, 99, 99, 3, 2, 1]
x1, x2, x3 = np.split(x, [3, 5])
print(x1, x2, x3)In [ ]:
grid = np.arange(16).reshape((4, 4))
gridIn [ ]:
upper, lower = np.vsplit(grid, [2])
print(upper)
print(lower)In [ ]:
left, right = np.hsplit(grid, [2])
print(left)
print(right)In [ ]:
In [ ]: