Type of NumPy Array Operations with Examples
NumPy (Numerical Python) is a powerful library in Python used for scientific computing and working with arrays. It provides a wide range of functions and operations for array manipulation, mathematical operations, linear algebra, statistics, and more. Here are some common types of NumPy operations:
-
Array Creation:
- np.array(): Create an array from a Python list or tuple.
- np.zeros(): Create an array filled with zeros.
- np.ones(): Create an array filled with ones.
- np.arange(): Create an array with evenly spaced values.
- np.linspace(): Create an array with a specified number of values within a range.
-
Array Manipulation:
- Indexing and Slicing: Access and modify elements or subarrays of an array.
- Reshaping: Change the shape (dimensions) of an array.
- Concatenation: Combine multiple arrays along a specified axis.
- Splitting: Split an array into multiple smaller arrays along a specified axis.
-
Mathematical Operations:
- Element-wise Operations: Perform mathematical operations on corresponding elements of two arrays.
- Broadcasting: Perform operations between arrays with different shapes by extending or duplicating values.
- Reduction Operations: Compute sum, mean, minimum, maximum, standard deviation, etc., along specified axes.
- Trigonometric Functions: sin(), cos(), tan(), arcsin(), arccos(), arctan(), etc.
- Exponential and Logarithmic Functions: exp(), log(), log10(), log2(), etc.
-
Linear Algebra:
- Matrix Operations: Matrix multiplication, element-wise multiplication, transpose, determinant, inverse, etc.
- Solving Equations: Solve linear equations and systems of equations.
- Eigenvalues and Eigenvectors: Compute eigenvalues and eigenvectors of a matrix.
-
Statistical Functions:
- Mean, median, standard deviation, variance, percentile, etc.
- Correlation and Covariance: Compute correlation coefficients and covariance between arrays.
- Random Number Generation: Generate random numbers from various probability distributions.
-
Array Comparison and Boolean Operations:
- Element-wise Comparison: Compare arrays element-wise and return a Boolean array.
- Logical Operations: Perform logical operations (and, or, not) on Boolean arrays.
1. Array Creation
import numpy as np
# Creating an array from a Python list
my_list = [1, 2, 3, 4, 5]
arr = np.array(my_list)
print(arr) # Output: [1 2 3 4 5]
# Creating an array filled with zeros
zeros_arr = np.zeros(5)
print(zeros_arr) # Output: [0. 0. 0. 0. 0.]
# Creating an array filled with ones
ones_arr = np.ones((2, 3)) # 2 rows, 3 columns
print(ones_arr)
# Output:
# [[1. 1. 1.]
# [1. 1. 1.]]
# Creating an array with evenly spaced values
range_arr = np.arange(1, 10, 2) # Start: 1, End: 10 (exclusive), Step: 2
print(range_arr) # Output: [1 3 5 7 9]
# Creating an array with a specified number of values within a range
linspace_arr = np.linspace(0, 1, 5) # Start: 0, End: 1, 5 values
print(linspace_arr) # Output: [0. 0.25 0.5 0.75 1. ]
2. Array Manipulation
import numpy as np
# Indexing and Slicing
arr = np.array([1, 2, 3, 4, 5])
print(arr[2]) # Output: 3
print(arr[1:4]) # Output: [2 3 4]
print(arr[::2]) # Output: [1 3 5]
# Reshaping
arr = np.arange(1, 10)
reshaped_arr = arr.reshape((3, 3)) # 3 rows, 3 columns
print(reshaped_arr)
# Output:
# [[1 2 3]
# [4 5 6]
# [7 8 9]]
# Concatenation
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
concatenated_arr = np.concatenate((arr1, arr2))
print(concatenated_arr) # Output: [1 2 3 4 5 6]
# Splitting
arr = np.array([1, 2, 3, 4, 5, 6])
split_arr = np.split(arr, 3) # Split into 3 equal-sized parts
print(split_arr)
# Output:
# [array([1, 2]), array([3, 4]), array([5, 6])]
3. Mathematical Operations
import numpy as np
# Element-wise Operations
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
sum_arr = arr1 + arr2
print(sum_arr) # Output: [5 7 9]
# Broadcasting
arr = np.array([1, 2, 3])
scalar = 2
multiplied_arr = arr * scalar
print(multiplied_arr) # Output: [2 4 6]
# Reduction Operations
arr = np.array([1, 2, 3, 4, 5])
sum_all = np.sum(arr)
print(sum_all) # Output: 15
sum_axis0 = np.sum(arr, axis=0)
print(sum_axis0) # Output: 15
# Trigonometric Functions
arr = np.array([0, np.pi/2, np.pi])
sin_arr = np.sin(arr)
print(sin_arr) # Output: [0.00000000e+00 1.00000000e+00 1.22464680e-16]
# Exponential and Logarithmic Functions
arr = np.array([1, 2, 3])
exp_arr = np.exp(arr)
print(exp_arr) # Output: [ 2.71828183 7.3890561 20.08553692]
log_arr = np.log(arr)
print(log_arr) # Output: [0. 0.69314718 1.09861229]
4. Linear Algebra
import numpy as np
# Matrix Operations
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
matrix_mult = np.matmul(matrix1, matrix2)
print(matrix_mult)
# Output:
# [[19 22]
# [43 50]]
# Solving Equations
A = np.array([[2, 3], [4, 5]])
b = np.array([6, 7])
x = np.linalg.solve(A, b)
print(x) # Output: [-1. 2.]
# Eigenvalues and Eigenvectors
matrix = np.array([[1, -2], [2, -3]])
eigenvalues, eigenvectors = np.linalg.eig(matrix)
print(eigenvalues) # Output: [-0.99999998 -1.00000002]
print(eigenvectors)
# Output:
# [[ 0.70710678 0.70710678]
# [-0.70710678 -0.70710678]]
5.Statistical Functions
import numpy as np
# Mean, median, standard deviation, variance, percentile
arr = np.array([1, 2, 3, 4, 5])
mean = np.mean(arr)
print(mean) # Output: 3.0
median = np.median(arr)
print(median) # Output: 3.0
std_dev = np.std(arr)
print(std_dev) # Output: 1.4142135623730951
variance = np.var(arr)
print(variance) # Output: 2.0
percentile = np.percentile(arr, 75)
print(percentile) # Output: 4.0
# Correlation and Covariance
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
correlation = np.corrcoef(arr1, arr2)
print(correlation)
# Output:
# [[1. 1.]
# [1. 1.]]
covariance = np.cov(arr1, arr2)
print(covariance)
# Output:
# [[1. 1.]
# [1. 1.]]
# Random Number Generation
random_nums = np.random.randn(3, 4) # 3 rows, 4 columns, from standard normal distribution
print(random_nums)
# Output:
# [[-0.23547022 -0.54880839 -1.11666087 -0.42451886]
# [-0.06494713 -0.27591135 0.1875496 -1.19226078]
# [ 0.53520464 0.40331663 0.03531517 -0.73222835]]
6. Array Comparison and Boolean Operations
import numpy as np
# Element-wise Comparison
arr1 = np.array([1, 2, 3])
arr2 = np.array([2, 2, 3])
comparison = arr1 == arr2
print(comparison) # Output: [False True True]
# Logical Operations
bool_arr = np.array([True, False, True])
logical_and = np.logical_and(bool_arr, ~bool_arr)
print(logical_and) # Output: [False False False]
logical_or = np.logical_or(bool_arr, ~bool_arr)
print(logical_or) # Output: [ True True True]
logical_not = np.logical_not(bool_arr)
print(logical_not) # Output: [False True False]