Table of Contents
ToggleNumPy makes performing arithmetic operations on arrays simple and easy. With NumPy, you can add, subtract, multiply, and divide entire arrays element-wise, meaning that each element in one array is operated on by the corresponding element in another array.
When performing arithmetic operations with arrays of different shapes, NumPy uses a feature called broadcasting. It automatically adjusts the shapes of the arrays so that the operation can be performed, extending the smaller array across the larger one as needed.
NumPy provides several arithmetic operations that are performed element-wise on arrays. These include addition, subtraction, multiplication, division, and power.
Addition in NumPy is performed element-wise. When two arrays of the same shape are added, corresponding elements are summed together. Broadcasting rules apply when arrays have different shapes −
# Open Compiler import numpy as np # Creating two arrays a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) # Adding arrays result = a + b print(result)
Output:
Following is the output obtained −
[5 7 9]
Subtraction in NumPy is also element-wise. Subtracting two arrays with the same shape returns an array where each element is the difference of the corresponding elements in the input arrays −
# Open Compiler import numpy as np # Creating two arrays a = np.array([10, 20, 30]) b = np.array([1, 2, 3]) # Subtracting arrays result = a - b print(result)
Output:
This will produce the following result −
[ 9 18 27]
Element-wise multiplication is performed using the * operator in NumPy. When multiplying arrays, each element of the first array is multiplied by the corresponding element in the second array −
# Open Compiler import numpy as np # Creating two arrays a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) # Multiplying arrays result = a * b print(result)
Output:
Following is the output of the above code −
[ 4 10 18]
Division is performed element-wise using the / operator in NumPy. It results in an array where each element is the quotient of the corresponding elements in the input arrays −
# Open Compiler import numpy as np # Creating two arrays a = np.array([10, 20, 30]) b = np.array([1, 2, 5]) # Dividing arrays result = a / b print(result)
Output:
The output obtained is as shown below −
[10. 10. 6.]
The power operation is performed element-wise using the ** operator in NumPy. Each element of the base array is raised to the power of the corresponding element in the exponent array −
# Open Compiler import numpy as np # Creating two arrays a = np.array([2, 3, 4]) b = np.array([1, 2, 3]) # Applying power operation result = a ** b print(result)
Output:
After executing the above code, we get the following output −
[ 2 9 64]
We can also use the numpy.power() function to raise elements of an array to the specified power. This function treats elements in the first input array as base and returns it raised to the power of the corresponding element in the second input array −
# Open Compiler
import numpy as np
a = np.array([10,100,1000])
print ('Our array is:')
print (a)
print ('\n')
print ('Applying power function:')
print (np.power(a,2))
print ('\n')
print ('Second array:')
b = np.array([1,2,3])
print (b)
print ('\n')
print ('Applying power function again:')
print (np.power(a,b))
Output:
It will produce the following output −
Our array is:
[ 10 100 1000]
Applying power function:
[ 100 10000 1000000]
Second array:
[1 2 3]
Applying power function again:
[ 10 10000 1000000000]
Advanced arithmetic operations in NumPy include operations such as modulo, floor division, and power. These operations handle more complex mathematical tasks and are performed element-wise, similar to basic arithmetic operations, but with additional functionality for modular arithmetic and exponentiation.
The modulo operation is performed using the % operator in NumPy. When applied to arrays, it operates element-wise, meaning each element of the first array is divided by the corresponding element in the second array, and the remainder is calculated −
# Open Compiler import numpy as np # Creating two arrays a = np.array([10, 20, 30]) b = np.array([3, 7, 8]) # Applying modulo operation result = a % b print(result)
Output:
The result produced is as follows −
[1 6 6]
We can also use the numpy.mod() function to calculate the element-wise remainder of division (modulus operation) between the elements of two arrays or between an array and a scalar.
This function returns the remainder when one array is divided by another array or scalar, applying the modulus operation element by element.
# Open Compiler
import numpy as np
a = np.array([10,20,30])
b = np.array([3,5,7])
print ('First array:')
print (a)
print ('\n')
print ('Second array:')
print (b)
print ('\n')
print ('Applying mod() function:')
print (np.mod(a,b))
print ('\n')
print ('Applying remainder() function:')
print (np.remainder(a,b))
Output:
Following is the output of the above code −
First array:
[10 20 30]
Second array:
[3 5 7]
Applying mod() function:
[1 0 2]
Applying remainder() function:
[1 0 2]
The floor division in NumPy is performed element-wise using the // operator. It returns the largest integer less than or equal to the division result −
# Open Compiler import numpy as np # Creating two arrays a = np.array([10, 20, 30]) b = np.array([3, 7, 8]) # Applying floor division result = a // b print(result)
Output:
We get the output as shown below −
[3 2 3]
Broadcasting allows NumPy to perform arithmetic operations on arrays of different shapes by virtually expanding the smaller array to match the shape of the larger array.
When a scalar is used with an array, broadcasting expands the scalar to match the shape of the array, allowing element-wise operations −
# Open Compiler import numpy as np # Creating an array a = np.array([[1, 2, 3], [4, 5, 6]]) # Scalar value scalar = 10 # Adding scalar to array result = a + scalar print(result)
Output:
Following is the output obtained −
[[11 12 13]
[14 15 16]]
When two arrays of different shapes are used in NumPy, broadcasting aligns their shapes according to broadcasting rules −
# Open Compiler import numpy as np # Creating arrays with different shapes a = np.array([[1, 2, 3], [4, 5, 6]]) b = np.array([10, 20, 30]) # Adding arrays result = a + b print(result)
Output:
This will produce the following result −
[[11 22 33]
[14 25 36]]
Aggregation functions in NumPy perform operations like sum, mean, min, and max across arrays, often using broadcasting to handle arrays of different shapes.
The NumPy sum operation calculates the sum of array elements over a specified axis or over the entire array if no axis is specified −
# Open Compiler import numpy as np # Creating an array a = np.array([[1, 2, 3], [4, 5, 6]]) # Summing elements result = np.sum(a) print(result) # Summing along axis 0 (columns) result_axis0 = np.sum(a, axis=0) print(result_axis0) # Summing along axis 1 (rows) result_axis1 = np.sum(a, axis=1) print(result_axis1)
Output:
Following is the output of the above code −
21
[5 7 9]
[ 6 15]
The NumPy mean operation calculates the average (arithmetic mean) of array elements over a specified axis or over the entire array −
# Open Compiler import numpy as np # Creating an array a = np.array([[1, 2, 3], [4, 5, 6]]) # Mean of elements result = np.mean(a) print(result) # Mean along axis 0 (columns) result_axis0 = np.mean(a, axis=0) print(result_axis0) # Mean along axis 1 (rows) result_axis1 = np.mean(a, axis=1) print(result_axis1)
Output:
The output obtained is as shown below −
3.5
[2.5 3.5 4.5]
[2. 5.]
The following functions are used to perform operations on arrays with complex numbers:
numpy.real(): Returns the real part of the complex data type argument.numpy.imag(): Returns the imaginary part of the complex data type argument.numpy.conj(): Returns the complex conjugate, which is obtained by changing the sign of the imaginary part.numpy.angle(): Returns the angle of the complex argument. The function has a degree parameter. If true, the angle in degrees is returned, otherwise the angle is in radians.In the following example, we are using NumPy functions: real(), imag(), conj(), and angle() to perform operations on an array with complex numbers −
# Open Compiler
import numpy as np
a = np.array([-5.6j, 0.2j, 11. , 1+1j])
print ('Our array is:')
print (a)
print ('\n')
print ('Applying real() function:')
print (np.real(a))
print ('\n')
print ('Applying imag() function:')
print (np.imag(a))
print ('\n')
print ('Applying conj() function:')
print (np.conj(a))
print ('\n')
print ('Applying angle() function:')
print (np.angle(a))
print ('\n')
print ('Applying angle() function again (result in degrees)')
print (np.angle(a, deg = True))
Output:
It will produce the following output −
Our array is:
[ 0.-5.6j 0.+0.2j 11.+0.j 1.+1.j ]
Applying real() function:
[ 0. 0. 11. 1.]
Applying imag() function:
[-5.6 0.2 0. 1. ]
Applying conj() function:
[ 0.+5.6j 0.-0.2j 11.-0.j 1.-1.j ]
Applying angle() function:
[-1.57079633 1.57079633 0. 0.78539816]
Applying angle() function again (result in degrees)
[-90. 90. 0. 45.]
Several routines are available in the NumPy package for operations on elements in an array. NumPy arrays support operations like addition, subtraction, and indexing for efficient data manipulation −
| Sr.No. | Operation & Description |
|---|---|
| 1 | numpy.add()Enables efficient element-wise addition for data manipulation. |
| 2 | numpy.subtract()Computes element-wise differences between two arrays efficiently. |
| 3 | numpy.multiply()Computes element-wise products between two arrays efficiently. |
| 4 | numpy.divide()Performs element-wise division, requiring non-zero, same-shaped arrays. |
| 5 | numpy.power()Raises elements of one array to another’s element-wise. |
| 6 | numpy.mod()Computes element-wise remainders of division between two arrays. |
| 7 | numpy.remainder()Computes element-wise remainders of division between two arrays. |
| 8 | numpy.divmod()Returns a tuple with quotient and remainder of division. |
| 9 | numpy.abs()Returns the positive absolute value of numbers. |
| 10 | numpy.absolute()Computes the absolute value of each array element efficiently. |
| 11 | numpy.fabs()Returns the positive magnitudes. |
| 12 | numpy.sign()Returns an element-wise indication of the sign of a number. |
| 13 | numpy.conj()Returns the complex conjugate, element-wise. |
| 14 | numpy.exp()Calculates the exponential of all elements in the input array. |
| 15 | numpy.expm1()Calculates exp(x)-1 for all elements in the array. |
| 16 | numpy.log()Natural logarithm, element-wise. |
| 17 | numpy.log1p()Computes element-wise natural logarithm of (1 + input array). |
| 18 | numpy.log2()Base-2 logarithm of x. |
| 19 | numpy.log10()Returns the base 10 logarithm of the input array, element-wise. |
| 20 | numpy.sqrt()Returns the non-negative square-root of an array, element-wise. |
| 21 | numpy.square()Returns the element-wise square of the input. |
| 22 | numpy.cbrt()Returns the cube-root of an array, element-wise. |
| 23 | numpy.reciprocal()Calculates the reciprocal of each element in arrays. |
Key Takeaway: Master NumPy arithmetic operations for efficient data manipulation at Vista Academy!
