• Post author:
  • Post category:NumPy / Python
  • Post last modified:March 27, 2024
  • Reading time:19 mins read
You are currently viewing Python NumPy Array Operations

NumPy is a powerful numerical computing library in Python that provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these elements. NumPy array operations are used to add(), substract(), multiply() and divide() two arrays. Python has a wide range of standard arithmetic operations, these help to perform normal functions of addition, subtraction, multiplication, and division.

Advertisements

The arithmetic operations take a minimum of two arrays as input and these arrays must be either of the same shape or should conform to array broadcasting rules. In this article, I will explain various functions to perform arithmetic operations on NumPy arrays with examples.

1. Quick Examples of NumPy Array Operations

If you are in a hurry, below are some quick examples of how to Python NumPy Array Operations.


# Quick examples of numpy array oerations

# Example 1: Adding the two arrays
arr2 = np.add(arr, arr1)

# Example 2: Subtracting the two arrays
arr2 = np.subtract(arr, arr1)
  
# Example 3: Multiplying the two arrays
arr2 = np.multiply(arr, arr1)
print(arr2)
  
# Example 4: Dividing the two arrays
arr2 = np.divide(arr, arr1)

# Example 5: Use numpy.power() 
# To calculating exponents of an array of numbers
arr = np.array([5, 3, 6, 9, 2, 4]) 
arr2 = np.power(arr,3)

# Example 6: Use numpy.power() with two arrays
arr = [2, 4, 6, 5, 3]
arr1 = [2, 3, 5, 4, 1]
arr2 = np.power(arr,arr1)

# Example 7: Use numpy.reciprocal() function
arr = np.array([50, 1.34, 3, 1, 25]) 
arr2 = np.reciprocal(arr)

# Example 8: Use reciprocal function
arr = np.array([75], dtype = int) 
arr2 = np.reciprocal(arr) 

# Example 9: Use numpy.mod() function
arr = np.array([7,16, 25]) 
arr1 = np.array([4,8,6]) 
arr2 = np.mod(arr,arr1) 

# Example 10: Use numpy.remainder() function
arr = np.array([7,16, 25]) 
arr1 = np.array([4,8,6]) 
arr2 = np.remainder(arr,arr1) 

2. Arithmetic Operations on NumPy array

Python contains a wide range of standard arithmetic operations. These operations help to perform normal functions like addition, subtraction, multiplication, and division such as, add(), subtract(), multiply(), and divide() respectively. The input arrays to these operations must be either of the same shapes or should conform to array broadcasting rules. In order to apply the arithmetic operations on the NumPy array, we have to initialize the array. Let’s create the NumPy array.


# Import numpy
import numpy as np

# Initializing the array
arr = np.arange(12, dtype = np.float_).reshape(3, 4) 
print("Origina array:\n",arr)

# Output:
# Origina array:
#  [[ 0.  1.  2.  3.]
#  [ 4.  5.  6.  7.]
#  [ 8.  9. 10. 11.]]

# Create the input array
arr1 = np.array([6, 12, 15, 18]) 
print("Origina array:\n",arr1)

# Output:
# Origina array:
#  [ 6 12 15 18]

2.1 Adding Two Arrays

The numpy.add() function is used to return the addition of two arrays element-wise. If the shape of two arrays is not the same, that is arr1.shape!=arr2.shape, they must be broadcastable to a common shape (which may be the shape of one or the other).

Following is the syntax of the numpy.add()


# Syntax of numpy.add()
numpy.add(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj], ufunc ‘add’)

Add our two NumPy arrays using numpy.add() function. It returns the addition of two arrays.


# Initializing the array
arr = np.arange(12, dtype = np.float_).reshape(3, 4) 
print("First array:\n",arr)
arr1 = np.array([6, 12, 15, 18]) 
print("Second array:\n",arr1)

# Add two arrays
arr2 = np.add(arr, arr1)
print("Adding two arrays:\n",arr2)

Yields below output.

numpy array operations

2.2 Subtracting the Two Arrays

The numpy.subtract() function is used to return the difference of two arrays element-wise. Following is the syntax of numpy.subtract()


# Syntax of numpy.subtract
numpy.subtract(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj], ufunc ‘subtract’)

when you use numpy.subtract() function on arr, arr1 NumPy arrays, you will get a difference of arr2 array.


# Subtracting the two arrays
arr2 = np.subtract(arr, arr1)
print("Subtracting array:\n",arr2)

# Output:
# Subtracting array:
# [[ -6. -11. -13. -15.]
# [ -2.  -7.  -9. -11.]
# [  2.  -3.  -5.  -7.]]

2.3 Multiplying Two Arrays

numpy.multiply() function is used to return the product of two arrays element-wise. Following is the syntax of the numpy.multiply()


# Syntax of numpy.multiply()
numpy.multiply(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj], ufunc ‘multiply’)

Using numpy.multiply() function on arr, arr1 NumPy arrays, you will get a product of arr2 NumPy array.


# Multiplying the two arrays
arr2 = np.multiply(arr, arr1)
print("Multiplying arrays:\n",arr2)

# Output:
# Multiplying arrays:
# [[  0.  12.  30.  54.]
# [ 24.  60.  90. 126.]
# [ 48. 108. 150. 198.]]

2.4 Dividing The Two Arrays

Array element from the first array is divided by elements from the second array (all happens element-wise). Both arr1 and arr2 must have the same shape and the element in arr2 must not be zero, otherwise, it will raise an error.

Following is the Syntax of the numpy.divide().


# Syntax of numpy.divide()
numpy.divide(arr1, arr2, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None) 

Here, the arr1 parameter is an input array that works as a dividend and arr2 is also an input array that works as the divisor. It returns an array with arr1/arr2(element-wise) as elements of the output array.


# Dividing the two arrays
arr2 = np.divide(arr, arr1)
print("Dividing arrays:\n",arr2)

# Output:
# Dividing arrays:
# [[0.         0.08333333 0.13333333 0.16666667]
# [0.66666667 0.41666667 0.4        0.38888889]
# [1.33333333 0.75       0.66666667 0.61111111]]

3. Use numpy.power() Arithmetic Operation

Array element from the first array is raised to the power of element from the second array(all happens element-wise). Both arr1 and arr2 must have the same shape and each element in arr1 must be raised to the corresponding positive value from arr2 otherwise, it will raise a Value Error.

Following is the syntax of the numpy.power().


# Syntax of numpy.power
numpy.power(arr1, arr2, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None) 

To calculate the element-wise power of a 1-dimensional NumPy array, you can use the numpy.power() function.

In the below example, the np.power(arr, 3) function raises each element of the 1-dimensional array arr to the power of 3. Each element of the original array is squared element-wise using the np.power() function. You can replace 3 with any other exponent value to calculate the element-wise power for the 1-dimensional array.


# Creating a 1D input array
arr = np.array([5, 3, 6, 9, 2, 4])
print("Original array:\n", arr)

# Use numpy.power() 
# To calculating exponents of an array of numbers
arr2 = np.power(arr,3)
print("After getting the element-wise power:\n", arr2)

# Output:
# Original array:
#  [5 3 6 9 2 4]
# After getting the element-wise power:
#  [125  27 216 729   8  64]

You can get exponents of two 1- D NumPy arrays element-wise. Here the first array ‘arr’ elements act as a base, and the second array ‘arr1’ elements act as an exponent. This function will return an array with elements of the first array raised to exponents in the second array(element-wise).


# Creating an 2D input array
arr = [2, 4, 6, 5, 3]
arr1 = [2, 3, 5, 4, 1]

# Use numpy.power() with two arrays
arr2 = np.power(arr,arr1)
print("After getting the element-wise power:\n", arr2)

# Output:
# After getting the element-wise power:
#  [   4   64 7776  625    3]

4. Use numpy.reciprocal() Operation

numpy.reciprocal() function is used to return the reciprocal of the argument, element-wise. Following is the syntax of the numpy.reciprocal()


# Syntax of numpy.reciprocal
numpy.reciprocal(x, /, out=None, *, where=True)

The numpy.reciprocal() function is used to find the reciprocal of each element in a NumPy array. The reciprocal of a number x is defined as 1/x.

In the below example, the original array arr contains the values [50, 1.34, 3, 1, 25]. The numpy.reciprocal() function is applied to each element of the array, resulting in the reciprocal of each element.


# Creating a 1D input array
arr = np.array([50, 1.34, 3, 1, 25]) 
print("Original array:\n", arr)

# Use numpy.reciprocal() function
arr2 = np.reciprocal(arr)
print("Reciprocal array:\n", arr2)

# Output:
# Original array:
#  [50.    1.34  3.    1.   25.  ]
# Reciprocal array:
#  [0.02       0.74626866 0.33333333 1.         0.04      ]

For integer arguments with an absolute value larger than 1, the result is always zero because of the way Python handles integer division. For integer zero the result is an overflow.

If you ever have an array containing zeros, be aware that the reciprocal of zero is represented as inf (infinity) in NumPy. You might want to handle such cases depending on your specific use case.


# Creating a 1D input array
arr = np.array([75], dtype = int)
print("Original array:\n", arr)

# Use reciprocal function
arr2 = np.reciprocal(arr) 
print("Reciprocal array:\n", arr2)

# Output:
# Original array:
#  [75]
# Reciprocal array:
#  [0]

5. Use numpy.mod() Operation

NumPy.mod() function is used to return the element-wise remainder of the division between two arrays arr1 and arr2 i.e. arr1 % arr2. It returns 0 when arr2 is 0 and both arr1 and arr2 are (arrays of) integers.

Following is the syntax of numpy.mod().


# Syntax
numpy.mod(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj], ufunc ‘remainder’)

The numpy.mod() function is used to find the element-wise remainder of the division of two arrays. It calculates the modulus (remainder) after division.


# Creating an 2D input array
arr = np.array([7,16, 25]) 
arr1 = np.array([4,8,6]) 

# Use numpy.mod() function
arr2 = np.mod(arr,arr1) 
print("Element-wise remainder(modulus) after division:\n", arr2)

# Output:
# Element-wise remainder(modulus) after division:
#  [3 0 1]

Alternatively, the numpy.remainder() function is similar to numpy.mod() and is used to find the element-wise remainder of the division of two arrays.

This code will produce the same result as the numpy.mod() example. Both functions are equivalent for the purpose of finding the remainder after division


# Use numpy.remainder() function
arr2 = np.remainder(arr,arr1) 
print("Element-wise remainder(modulus) after division:\n", arr2)

# Output:
# Element-wise remainder(modulus) after division:
# [3 0 1]

Frequently Asked Questions

What is NumPy?

NumPy is a powerful numerical computing library in Python. It provides support for large, multi-dimensional arrays and matrices, along with mathematical functions to operate on these elements.

What are some common array operations in NumPy?

Common array operations include element-wise operations (addition, subtraction, multiplication, division), matrix operations, transposing, sum, mean, min, max, indexing, slicing, universal functions (ufunc), broadcasting, and linear algebra operations.

How do I perform element-wise operations on NumPy arrays?

Performing element-wise operations on NumPy arrays is straightforward. NumPy supports standard arithmetic operations(+, -, *, /), and these operations are applied element-wise to arrays.

How do I perform linear algebra operations in NumPy?

NumPy provides functions for linear algebra operations, such as matrix inversion (np.linalg.inv()), determinant (np.linalg.det()), and eigenvalues and eigenvectors (np.linalg.eig()).

Can I perform operations on a subset of a NumPy array?

You can perform operations on a subset of a NumPy array using indexing and slicing. NumPy allows you to access and modify specific elements or slices of an array efficiently.

What are universal functions (ufunc) in NumPy?

Universal functions are functions that operate element-wise on NumPy arrays. Examples include np.sin(), np.cos(), and np.exp().

Conclusion

In this article, I have explained how to use NumPy array operations by using arithmetic operations like numpy.power(), numpy.reciprocal() and numpy.mod() functions with examples.

Happy Learning!!

References

Malli

Malli is an experienced technical writer with a passion for translating complex Python concepts into clear, concise, and user-friendly articles. Over the years, he has written hundreds of articles in Pandas, NumPy, Python, and takes pride in ability to bridge the gap between technical experts and end-users.