How to Divide Arrays in NumPy: Syntax and Examples
To divide arrays element-wise in NumPy, use the
/ operator or the numpy.divide() function. Both methods perform division on each pair of elements from the input arrays of the same shape.Syntax
You can divide arrays in NumPy using two main ways:
array1 / array2: Divides elements ofarray1by corresponding elements ofarray2.numpy.divide(array1, array2): A function that does the same element-wise division.
Both require arrays to have the same shape or be broadcastable.
python
import numpy as np # Using / operator a = np.array([10, 20, 30]) b = np.array([2, 5, 3]) c = a / b # Using numpy.divide function d = np.divide(a, b)
Example
This example shows how to divide two arrays element-wise using both the / operator and numpy.divide() function.
python
import numpy as np a = np.array([12, 24, 36]) b = np.array([3, 6, 9]) result_operator = a / b result_function = np.divide(a, b) print("Division using / operator:", result_operator) print("Division using numpy.divide():", result_function)
Output
Division using / operator: [4. 4. 4.]
Division using numpy.divide(): [4. 4. 4.]
Common Pitfalls
Common mistakes when dividing arrays in NumPy include:
- Dividing arrays of incompatible shapes without broadcasting, which causes errors.
- Dividing by zero elements, which results in warnings and
infornanvalues. - Using integer arrays and expecting float division; integer division truncates decimals.
Always check array shapes and handle zeros carefully.
python
import numpy as np a = np.array([10, 20, 30]) b = np.array([2, 0, 5]) # This will produce a warning and inf for division by zero result = a / b print(result) # To avoid integer division truncation, use float arrays result_float = a.astype(float) / b print(result_float)
Output
[ 5. inf 6.]
[ 5. nan 6.]
Quick Reference
| Operation | Description | Example |
|---|---|---|
| / operator | Element-wise division of two arrays | a / b |
| numpy.divide(a, b) | Function for element-wise division | np.divide(a, b) |
| Broadcasting | Arrays with compatible shapes divide element-wise | a (3,) / b (1,) |
| Division by zero | Results in inf or nan with warning | np.array([1]) / np.array([0]) |
| Integer division | Truncates decimals if arrays are int | np.array([5]) / np.array([2]) == 2 |
Key Takeaways
Use the / operator or numpy.divide() for element-wise array division in NumPy.
Ensure arrays have compatible shapes or can be broadcasted to avoid errors.
Watch out for division by zero which causes warnings and infinite or NaN values.
Convert integer arrays to float to get decimal results instead of truncated integers.
Broadcasting allows division between arrays of different but compatible shapes.