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)
Calculating the mean of an ndarray
np.mean(arr)
Find the mean along the columns by specifying the axis=parameter
np.mean(arr, axis=0)
np.mean(arr, axis=1)
Finding the index of the maximum value in an ndarray
Find the location of the maximum value in the ndarray
np..argmax(arr)
Find the location of the maximum value on each row
np.argmax(arr, axis=1)
Calculating the cumulative sum of elements of an ndarray
np.cumsum(arr)
A cumulative sum is an array of a running total.
A sum is a single number.
Applying the axis=parameter to the cumsum method works similarly
np.cumsum(arr, axis=1)
Finding NaNs in an ndarray
Set the second row to np.nan
arr[1, :] = np.nan
np.isnan(arr)
Finding the truth values of x1>x2 two ndarrays
arr1 = np.random.randn(9).reshape((3,3))
arr2 = np.random.randn(9).reshape((3,3))
np.greater(arr1, arr2)
arr1 > arr2
any and all Boolean operations on ndarrays
arr_bool = (arr > -0.5) & (arr < 0.5)
Return True if any element is True and otherwise returns False
arr_bool.any()
arr_bool.any(axis=1)
Return True when all elements are True, and False otherwise
arr_bool.all()
arr_bool.all(axis=1)
Sorting ndarrays
arr1D = np.random.randn(10)
Sorting straightforward
np.sort(arr1D)
Creates an array of indices that represent the location of each element in a sorted array
np.argsort(arr1D)
Searching within ndarrays
Start with an ndarray with consecutive values
arr1 = np.array(range(1,11));
arr2 = arr1 * 1000;
cond = np.random.randn(10) > 0;
Select values from one ndarray or another, depending on the condition being True or False
np.where(cond, arr1, arr2)
File operations on ndarrays
File operations with text files
arr = np.random.randn(10)
np.savetxt('arr.csv', arr, fmt='%0.2lf', delimiter=',')
arr_new = np.loadtxt('arr.csv', delimiter=',')
File operations with binary files
np.save('arr', arr)
arr_new = np.load('arr.npy')
arr == arr_new



