import numpy as np
Get info
np.info(np.array)
Create numpy array from python array
mylist = [1, 2, 3]
np.array(mylist)
Create an array of evenly (integers)
np.arange(0, 11)
np.arange(0, 11, 2) # step size = 2
Create an array of zeros
np.zeros(3)
np.zeros((3,5))
Create an array of ones
np.ones((3,3))
Create an array of evenly spaced values (number of samples)
np.linspace(0, 10, 3) # strat, end, numOfelements
np.linspace(0, 10, 20)
Create an identity matrix
np.eye(3)
Create an array with random values
np.random.rand(4) # uniform dist between 0..1
np.random.rand(4, 3)
np.random.randn(3, 3) # standard normal dist
np.random.randint(1, 100, 5) # start, end, numOfElements
np.random.randint(1, 100, (2,3))
Reshaping arrays
arr = np.arange(25)
arr.shape
arr = arr.reshape(5, 5)
arr.shape
arr
arr.dtype
arr = np.arange(1, 11)
arr
Selecting a simple value
arr[0]
Value of a range
arr[2:5]
arr[:5] # start begining up to 5
arr[5:] # from index to the end
Broadcasting
arr
arr[0:5] = 100
arr
Slicing
arr = np.arange(1, 11)
arr
slice_of_arr = arr[0:5] # a pointer to the original array
slice_of_arr
slice_of_arr[:] = 99 # indexing all elements
slice_of_arr
arr
Copy
arr_copy = arr.copy()
arr_copy
arr_copy[:] = 100
arr_copy
arr
arr_2d = np.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]])
arr_2d
arr_2d.shape # rows, cols
arr_2d[0] # first row
arr_2d[1, 1] # a value
arr_2d[:2] # first two rows
arr_2d[:2, 1:] # first two rows and last two cols
Selecting more dimensions
arr = np.arange(32)
arr_3d = arr.reshape(8, 4)
arr_3d
arr_3d[0, ...] # first row and all the other dimensions
arr_3d = arr.reshape(2, 4, 4)
arr_3d
arr_3d[..., 0] # all dimensions and the first of the last one
Conditional selection
arr = np.arange(1, 11)
arr
arr > 4
arr[arr > 4]
arr = np.arange(0, 10)
arr
arr + 5
arr * 2
arr + arr
arr / arr
1 / arr
np.sqrt(arr)
np.sin(arr)
arr.sum()
arr.max()
2 Dim
arr_2d =np.arange(0, 25).reshape(5, 5)
arr_2d
arr_2d.sum()
arr_2d.sum(axis=0) # sum of the cols
arr_2d.sum(axis=1) # sum of the rows
Transpose
arr_2d.T # np.transpose(arr_2d) is the same
Flatten
np.ravel(arr_2d) # flatten
Append
arr = np.arange(0, 5)
arr
np.append(arr, [5])
np.insert(arr, 1, 5) # to the first index insert value 5
np.delete(arr, [1])