NumPy - Arithmetic Operations

NumPy Arithmetic Operations

NumPy 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.

Basic NumPy Arithmetic Operations

NumPy provides several arithmetic operations that are performed element-wise on arrays. These include addition, subtraction, multiplication, division, and power.

NumPy Array Addition

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 −

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)

Following is the output obtained −

[5 7 9]

NumPy Array Subtraction

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 −

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)

This will produce the following result −

[ 9 18 27]

NumPy Array Multiplication

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 −

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)

Following is the output of the above code −

[ 4 10 18]

NumPy Array Division

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 −

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)

The output obtained is as shown below −

[10. 10.  6.]

NumPy Array Power Operation

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 −

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)

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 −

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))

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 NumPy Arithmetic Operations

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.

NumPy Modulo Operation

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 −

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)

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.

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)) 

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]

NumPy Floor Division

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 −

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)

We get the output as shown below −

[3 2 3]

NumPy Arithmetic Operations with Broadcasting

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.

Scalar and Array Operations in NumPy

When a scalar is used with an array, broadcasting expands the scalar to match the shape of the array, allowing element-wise operations −

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)

Following is the output obtained −

[[11 12 13]
 [14 15 16]]

Array with Different Shapes in NumPy

When two arrays of different shapes are used in NumPy, broadcasting aligns their shapes according to broadcasting rules −

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)

This will produce the following result −

[[11 22 33]
 [14 25 36]]

NumPy Aggregation Functions

Aggregation functions in NumPy perform operations like sum, mean, min, and max across arrays, often using broadcasting to handle arrays of different shapes.

NumPy Sum Operation

The NumPy sum operation calculates the sum of array elements over a specified axis or over the entire array if no axis is specified. −

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)

Following is the output of the above code −

21
[5 7 9]
[ 6 15]

NumPy Mean Operation

The NumPy mean operation calculates the average (arithmetic mean) of array elements over a specified axis or over the entire array −

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)

The output obtained is as shown below −

3.5
[2.5 3.5 4.5]
[2. 5.]

NumPy Array Operations with Complex Numbers

The following functions are used to perform operations on array 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 degree parameter. If true, the angle in the degree is returned, otherwise the angle is in radians.

Example

In the following example, we are using NumPy functons: real(), imag(), conj() and angle() to perform operations on array with complex numbers −

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))

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.]
© 2024 All rights reserved. | Made With 🤍 By The_MAK Team