NUMPY
NumPy is a crucial library for numerical operations in Python.
1. Importing NumPy
import numpy as np
2. Creating Arrays
NumPy arrays are the core object for all computations.
arr = np.array([1, 2, 3, 4, 5])
print(arr) # Output: [1 2 3 4 5]
Zeros array:
zeros_arr = np.zeros((2, 3)) # 2x3 array of zeros
print(zeros_arr)
# Output:
# [[0. 0. 0.]
# [0. 0. 0.]]
Ones array:
ones_arr = np.ones((2, 3))
print(ones_arr)
# Output:
# [[1. 1. 1.]
# [1. 1. 1.]]
Arange (range of numbers):
arr_range = np.arange(0, 10, 2) # From 0 to 10 with step 2
print(arr_range) # Output: [0 2 4 6 8]
Linspace (evenly spaced values):
arr_linspace = np.linspace(0, 1, 5) # 5 numbers between 0 and 1
print(arr_linspace)
# Output: [0. 0.25 0.5 0.75 1. ]
3. Array Indexing and Slicing
Accessing elements:
arr = np.array([1, 2, 3, 4, 5])
print(arr[0]) # Output: 1 (accessing the first element)
Slicing:
arr = np.array([1, 2, 3, 4, 5])
print(arr[1:4]) # Output: [2 3 4] (elements from index 1 to 3)
Fancy indexing:
arr = np.array([1, 2, 3, 4, 5])
print(arr[[0, 2, 4]]) # Output: [1 3 5] (using a list of indices)
Boolean indexing:
arr = np.array([1, 2, 3, 4, 5])
print(arr[arr > 2]) # Output: [3 4 5] (elements greater than 2)
4. Array Operations
Arithmetic operations:
arr = np.array([1, 2, 3])
print(arr + 1) # Output: [2 3 4]
print(arr * 2) # Output: [2 4 6]
Element-wise operations (using functions):
arr = np.array([1, 2, 3])
print(np.sqrt(arr)) # Output: [1. 1.41421356 1.73205081] (square root
of each element)
print(np.exp(arr)) # Output: [ 2.71828183 7.3890561 20.08553692]
(exponential of each element)
print(np.min(arr)) # Output: 1
print(np.max(arr)) # Output: 5
5. Reshaping and Sum, Mean, Min, Max:
arr = np.array([1, 2, 3, 4, 5])
print(np.sum(arr)) # Output: 15
print(np.mean(arr)) # Output: 3.0
Resizing Arrays
Reshaping:
arr = np.array([1, 2, 3, 4, 5, 6])
reshaped_arr = arr.reshape((2, 3)) # Convert 1D array to 2D
print(reshaped_arr)
# Output:
# [[1 2 3]# [4 5 6]]
Flattening:
arr_2d = np.array([[1, 2], [3, 4]])
flattened = arr_2d.flatten()
print(flattened) # Output: [1 2 3 4]
Transposing:
arr_2d = np.array([[1, 2], [3, 4]])
transposed = arr_2d.T
print(transposed)
# Output:
# [[1 3]
# [2 4]]
6. Random Module
Random Numbers:
rand_arr = np.random.rand(2, 3) # Random numbers between 0 and 1 in 2x3 shape
print(rand_arr)
Random Integers:
rand_ints = np.random.randint(0, 10, size=(3, 3)) # Random integers between 0
and 10
print(rand_ints)
Random Choice:
choices = np.random.choice([1, 2, 3, 4, 5], size=3) # Randomly choose
elements
print(choices)
7. Statistical Operations
Mean, Median, Standard Deviation:
arr = np.array([1, 2, 3, 4, 5])
print(np.mean(arr)) # Output: 3.0
print(np.median(arr)) # Output: 3.0
print(np.std(arr)) # Output: 1.4142135623730951
Variance and Percentiles:
print(np.var(arr)) # Output: 2.0
print(np.percentile(arr, 50)) # Output: 3.0 (50th percentile = median)
8. Concatenation and Stacking Arrays
Concatenate:
arr1 = np.array([1, 2])
arr2 = np.array([3, 4])
concat_arr = np.concatenate((arr1, arr2))
print(concat_arr) # Output: [1 2 3 4]
Stacking:
arr1 = np.array([1, 2])
arr2 = np.array([3, 4])
vstack_arr = np.vstack((arr1, arr2)) # Stack arrays vertically (row-wise)
print(vstack_arr)
# Output:
# [[1 2]
# [3 4]]
hstack_arr = np.hstack((arr1, arr2)) # Stack arrays horizontally (column-
wise)
print(hstack_arr) # Output: [1 2 3 4]
9. Set Operations
Unique elements:
arr = np.array([1, 2, 2, 3, 4, 4, 5])
unique_arr = np.unique(arr)
print(unique_arr) # Output: [1 2 3 4 5]
Union, Intersection, and Difference:
arr1 = np.array([1, 2, 3])
arr2 = np.array([3, 4, 5])
print(np.union1d(arr1, arr2)) # Output: [1 2 3 4 5]
print(np.intersect1d(arr1, arr2)) # Output: [3]
print(np.setdiff1d(arr1, arr2)) # Output: [1 2]
10. Handling Missing Data (NaN)
Handling missing data is an important part of data analysis.
Detect NaN values:
arr = np.array([1, np.nan, 3])
print(np.isnan(arr)) # Output: [False True False]
Replacing NaN values:
arr = np.array([1, np.nan, 3])
arr_cleaned = np.nan_to_num(arr, nan=0) # Replace NaN with 0
print(arr_cleaned) # Output: [1. 0. 3.]
11. Linear Algebra
Dot Product:
arr1 = np.array([1, 2])
arr2 = np.array([3, 4])
dot_product = np.dot(arr1, arr2)
print(dot_product) # Output: 11
Matrix Multiplication:
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
matrix_mult = np.dot(arr1, arr2)
print(matrix_mult)
# Output:
# [[19 22]
# [43 50]]
Inverse of a Matrix:
arr = np.array([[1, 2], [3, 4]])
inv_arr = np.linalg.inv(arr)
print(inv_arr)
# Output:
# [[-2. 1. ]
# [ 1.5 -0.5]]
INBUILT FUNCTIONS
1. Array Creation Functions
np.array(): Create a NumPy array from a Python list or other array-like object.
np.zeros(): Create an array of zeros with a specified shape.
np.ones(): Create an array of ones with a specified shape.
np.empty(): Create an array without initializing its values (it may contain random
values).
np.arange(): Generate values in a range (like range() but returns a NumPy array).
np.linspace(): Generate evenly spaced numbers over a specified interval.
np.eye(): Create a 2D identity matrix (diagonal 1s, rest 0s).
np.full(): Create an array filled with a constant value.
2. Array Manipulation
np.reshape(): Reshape an array to a new shape.
np.ravel(): Flatten a multi-dimensional array into 1D.
np.transpose(): Transpose an array (swap rows with columns).
np.concatenate(): Join two or more arrays along a specified axis.
np.stack(): Stack arrays along a new axis.
np.split(): Split an array into multiple sub-arrays.
np.append(): Append values to the end of an array.
np.insert(): Insert values into an array at specified indices.
np.delete(): Delete elements from an array at specified indices.
3. Mathematical Functions
np.add(): Add two arrays element-wise.
np.subtract(): Subtract two arrays element-wise.
np.multiply(): Multiply two arrays element-wise.
np.divide(): Divide two arrays element-wise.
np.power(): Raise each element of an array to the power of a number.
np.mod(): Compute the remainder of division element-wise.
np.sqrt(): Compute the square root of each element.
np.log(): Compute the natural logarithm of each element.
np.exp(): Compute the exponential of each element.
np.abs(): Compute the absolute value of each element.
np.round(): Round elements of an array to the nearest integer.
np.floor(): Round elements down to the nearest integer.
np.ceil(): Round elements up to the nearest integer.
4. Statistical Functions
np.mean(): Compute the mean (average) of array elements.
np.median(): Compute the median of array elements.
np.std(): Compute the standard deviation of array elements.
np.var(): Compute the variance of array elements.
np.sum(): Compute the sum of array elements.
np.min(): Find the minimum element in an array.
np.max(): Find the maximum element in an array.
np.argmin(): Find the index of the minimum element.
np.argmax(): Find the index of the maximum element.
np.percentile(): Compute the nth percentile of array elements.
np.corrcoef(): Compute the correlation coefficient matrix.
np.cov(): Compute the covariance matrix.
5. Linear Algebra Functions
np.dot(): Compute the dot product of two arrays.
np.linalg.inv(): Compute the inverse of a matrix.
np.linalg.det(): Compute the determinant of a matrix.
np.linalg.eig(): Compute the eigenvalues and eigenvectors of a matrix.
np.linalg.solve(): Solve a system of linear equations.
np.linalg.svd(): Compute the singular value decomposition of a matrix.
6. Random Number Generation
np.random.rand(): Generate random values between 0 and 1 (uniform distribution).
np.random.randn(): Generate random values from a normal distribution (mean = 0, std
= 1).
np.random.randint(): Generate random integers within a specified range.
np.random.choice(): Randomly choose elements from an array.
np.random.shuffle(): Shuffle the elements of an array in place.
np.random.seed(): Set the seed for random number generation (to get reproducible
results).
7. Array Operations
np.sum(): Compute the sum of elements along a specified axis.
np.prod(): Compute the product of elements along a specified axis.
np.cumsum(): Compute the cumulative sum of elements.
np.cumprod(): Compute the cumulative product of elements.
np.diff(): Compute the difference between adjacent elements.
np.unique(): Find the unique elements in an array.
np.unique() (return indices): Return the indices of unique elements.
np.intersect1d(): Find the intersection of two arrays.
np.setdiff1d(): Find the set difference of two arrays.
8. Boolean Operations
np.any(): Check if any element of an array is True.
np.all(): Check if all elements of an array are True.
np.isin(): Test if elements of an array are present in another array.
np.isnan(): Test if elements are NaN.
9. Miscellaneous Functions
np.argsort(): Return the indices that would sort an array.
np.searchsorted(): Find indices where elements should be inserted to maintain order.
np.isclose(): Test if two arrays are element-wise equal within a tolerance.
np.clip(): Limit the values in an array to a specified range.
np.delete(): Delete elements from an array.
np.repeat(): Repeat elements of an array.
np.tile(): Repeat an array to create a larger array.
10. Array Information Functions
np.shape(): Return the shape (dimensions) of an array.
np.size(): Return the total number of elements in an array.
np.ndim(): Return the number of dimensions (axes) of an array.
np.dtype(): Return the data type of an array's elements.
np.itemsize(): Return the size (in bytes) of each element of an array.
np.nbytes(): Return the total number of bytes consumed by an array.
11. Set Operations
np.union1d(): Compute the union of two arrays.
np.intersect1d(): Compute the intersection of two arrays.
np.setdiff1d(): Compute the set difference between two arrays.
np.setxor1d(): Compute the set exclusive-or (symmetric difference) between two
arrays.
12. Set Operations for Multidimensional Arrays
np.unique(): Return sorted, unique elements of an array.