Python - NumPy Part 3: Array Operations
NumPy supports a wide range of mathematical operations, both element-wise and matrix-wise.
Examples and Explanation
Element-Wise Operations
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(a + b) # Output: [5 7 9]
Explanation: Operations like addition, subtraction, and multiplication are applied element-wise.
Broadcasting
print(a * 2) # Output: [2 4 6]
Explanation: Broadcasting allows operations between arrays of different shapes, making it efficient for scalar multiplication.
Matrix Multiplication
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
print(np.dot(matrix1, matrix2))
# Output:
# [[19 22]
# [43 50]]
Explanation: Use np.dot() for matrix multiplication, essential in linear algebra applications.
Statistical Functions
print(np.mean(a)) # Output: 2.0
print(np.max(a)) # Output: 3
Explanation: NumPy provides statistical functions like mean, max, and min to analyze data arrays.
Aggregations
print(np.sum(matrix1)) # Output: 10
Explanation: Aggregations like sum and product are performed efficiently on entire arrays.