Element-wise arithmetic lets you do math on each item in a list or array separately. It helps you quickly calculate results for many numbers at once.
0
0
Element-wise arithmetic in NumPy
Introduction
Adding sales numbers from two different stores day by day.
Multiplying each pixel value in an image by a brightness factor.
Subtracting temperatures recorded on two different days to find the difference.
Dividing total costs by number of items to find cost per item.
Syntax
NumPy
result = array1 <operator> array2
# where <operator> can be +, -, *, /, etc.Both arrays should have the same shape or be compatible for broadcasting.
Operations happen on each pair of elements at the same position.
Examples
Adds each element of arr1 to the corresponding element of arr2.
NumPy
import numpy as np arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) result = arr1 + arr2 print(result)
Divides each element of arr1 by the corresponding element of arr2.
NumPy
import numpy as np arr1 = np.array([10, 20, 30]) arr2 = np.array([2, 4, 5]) result = arr1 / arr2 print(result)
Multiplies each element of arr1 by 3 (broadcasting with a single number).
NumPy
import numpy as np arr1 = np.array([1, 2, 3]) result = arr1 * 3 print(result)
Sample Program
This program adds sales numbers from two stores for each day to find total daily sales.
NumPy
import numpy as np # Create two arrays representing daily sales from two stores store1_sales = np.array([100, 150, 200, 250]) store2_sales = np.array([80, 120, 160, 200]) # Calculate total sales per day by adding element-wise total_sales = store1_sales + store2_sales print("Store 1 sales:", store1_sales) print("Store 2 sales:", store2_sales) print("Total sales per day:", total_sales)
OutputSuccess
Important Notes
If arrays have different shapes, numpy tries to 'broadcast' smaller arrays to match larger ones.
Be careful with division by zero when doing element-wise division.
Element-wise operations are much faster than looping through elements manually.
Summary
Element-wise arithmetic applies math operations to each pair of elements in arrays.
Arrays must be the same shape or compatible for broadcasting.
This method is useful for quick and easy calculations on many numbers at once.