Creating NumPy ndarrays
import numpy as np
Creating 1D ndarrays
arr1D = np.array([1.1, 2.2, 3.3, 4.4, 5.5]);
Inspect the type of the array
type(arr1D)
Creating 2D ndarrays
arr2D = np.array([1, 2],[3, 4])
Creating any-dimension ndarrays
arr4D = np.array(range(16))reshape.((2, 2, 2, 2))
Creating an ndarray with np.zeros(…)
Creates an ndarray populated with all 0s
np.zeros(shape=(2, 5))
Creating an ndarray with np.ones(…)
Each value is assigned a value of 1
np.ones(shape=(2,2))
Creating an ndarray with np.identity(…)
np.identity(3)
Creating an ndarray with np.arange(…)
np.arrange(5)
Creating an ndarray with np.random.randn(…)
Generates an ndarray of specified dimensions, with each element populated with random values drawn from a standard normal distribution (mean=0, std=1)
np.random.randn(2,2)
Data types used with NumPy ndarrays
Each element in an ndarray has the same data type.
Common data types used are np.int32, np.float64, float128, and np.bool.
np.float128 is not supported on Windows.
Creating a numpy.float64 array
np.array([-1, 0, 1], dtype=np.float64)
Creating a numpy.bool array
np.array([-1, 0, 1], dtype=np.bool)
0 gets converted to False, and all other values get converted to True.
ndarrays’ dtype attribute
arr1D.dtype
Converting underlying data types of ndarray with numpy.ndarrays.astype(…)
arr1D.astype(np.int64).dtype
Indexing of ndarrays
Direct access to an ndarray’s element
arr = np.random.randn(3, 3)
arr[0]
arr[0][1]
arr[0,1]
arr[-1]
ndarray slicing
Accessing all ndarray elements after the first one
arr[1:]
Fetching all rows, starting from row 2 and columns 1 and 2
arr[1:, :2]
Slicing with negative indices
arr[1:2, -2:-1]
Slicing with no indices
arr[:][2]
arr[:][:]
Setting values of a slice to 0
arr1 = arr[1:2]
arr1[:] = 0
The operation on the arr1 slice also changed the original arr ndarray.
Create a copy of an ndarray
arr_copy = arr.copy()
arr_copy[1:2] = 1
Boolean indexing
arr = np.random.randn(3,3)
arr < 0
arr[(arr < 0)]
(arr > -1) & (arr < 1)
arr[(arr > -1) & (arr < 1)]
Indexing with arrays
arr[[0,2]]
arr[[0,2],[1]]
arr[2,0]
Basic ndarray operation
Use an arr2D ndarray
arr2D
Scalar multiplication with an ndarray
arr2D * 4
Linear combinations of ndarrays
2*arr2D + 3*arr2D
Exponentiation of ndarrays
arr2D ** 2
Addition of an ndarray with a scalar
arr2D + 10
Transposing a matrix
arr2D.transpose()
Changing the layout of an ndarray
arr2D.reshape((4,1))
arr = np.random.randn(9),reshape((3,3))
Finding the minimum value in an ndarray
np.min(arr)
Calculating the absolute value
np.abs(arr)



