In this article, we will be learning how we can perform basic mathematical operations using Numpy. Our aim for this article is to learn about numpy.sum(), numpy.subtract(), numpy.multiply(), numpy.dot() and numpy.divide(). So as you can see these numpy functions are used to do basic operations of mathematics that are needed in machine learning or data science projects.
Let’s learn about them but before that, let us import the numpy library.
import numpy as np
We will start this tutorial with sum function
Numpy Sum : np.sum()
Now, let’s look at what are the parameters that the numpy sum function includes and how we can use it.
Syntax
As we can see there are seven parameters used in np.sum() or numpy.sum() operation. They are described as follows:
a : array_like – This is the array that is passed to the function, the elements of this array are added.
axis : None or int or tuple of ints (optional) – Axis or axes along which a sum is performed. This parameter can have either int or tuple of ints as its value
dtype : dtype (optional) – This tells us about the type of array returned by np.sum() function
out : ndarray (optional) – Alternative output array in which to place the result.
keepdims : bool (optional) – This parameter takes a boolean value. If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
initial : scalar (optional) – Starting value for the sum, this value is assumed for sum at the beginning of execution.
where : array_like of bool (optional) – This is the last parameter of np.sum() or numpy.sum() function, it tells which elements to include in the sum.
Example 1:
np.sum([36, 25])
61
Example 2: Understanding the use of axis parameter
np.sum([[4, 9], [8, 7]], axis=0)
array([12, 16])
Example 3: Understanding the use of axis parameter
Here we have provided the value of the axis parameter as ‘1’. So the array values 4 & 9 and 8 & 7 are added.
np.sum([[4, 9], [8, 7]], axis=1)
array([13, 15])
Example 4: Using “Initial” Parameter
np.sum([9], initial=43)
52
Example 5: Performing sum operation using ‘+’ operator
We can also perform addition operation by using ‘+’ operator, apart from using numpy sum()
a = np.array([5,2])
a
array([5, 2])
b = np.array([2,7])
b
array([2, 7])
a + b
array([7, 9])
Continuing this tutorial, let’s learn about how subtract operation works.
Numpy Subtract : np.subtract()
For performing subtract operation, we use numpy.subtract() or np.subtract() function.
Syntax
np.subtract(x1,x2,out=some_value,where=some_value,kwargs)
out : ndarray, None, or tuple of ndarray and None (optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.
where : array_like – (optional) – This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value.
kwargs – This parameter is used for other keyword arguments
The final output of numpy.subtract() or np.subtract() function is y : ndarray, this array gives difference of x1 and x2, element-wise.
Example 1:
Here in this first example, we have provided x1=7.0 and x2=4.0
np.subtract(7.0, 4.0)
3.0
Example 2:
This example of np.subtract() shows how we use np.arange() function for reshaping the array and then the results are further used for input to np.subtract() function
x1 = np.arange(9.0)
x1
array([0., 1., 2., 3., 4., 5., 6., 7., 8.])
x1 = np.arange(9.0).reshape((3, 3))
x1
array([[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]])
x2 = np.arange(3.0)
x2
array([0., 1., 2.])
Now, the x2 array is subtracted from x1 array below.
np.subtract(x1, x2)
array([[0., 0., 0.], [3., 3., 3.], [6., 6., 6.]])
Example 3: Performing subtraction using ‘-‘ operator
We can also perform subtraction operation by using ‘-‘ operator, apart from using numpy subtract()
a = np.array([9,1])
b = np.array([2,8])
a - b
array([ 7, -7])
[adrotate banner=”3″]
Moving on now to the multiply operation using numpy.
Numpy Multiply : np.multiply()
The multiply operation is performed with the help of numpy.multiply()
In this syntax of np.multiply(), we will look at the parameters used in this function
Syntax
numpy.multiply(x1, x2, /, out=None, , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj])
x1, x2 : array_like – The arrays to be subtracted from each other. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None (optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.
where : array_like – (optional) – This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value.
kwargs – This parameter is used for other keyword arguments
The final output of numpy.multiply() or np.multiply() function is y : ndarray, this array gives product of x1 and x2, element-wise.
Example 1:
np.multiply(7.0, 5.0)
35.0
Example 2:
This example of np.multiply() shows how we use np.arange() function for reshaping the array and then the results are further used for input to np.multiply() function
x1 = np.arange(9.0)
x1
array([0., 1., 2., 3., 4., 5., 6., 7., 8.])
x1 = np.arange(9.0).reshape((3, 3))
x1
array([[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]])
x2 = np.arange(3.0)
x2
array([0., 1., 2.])
np.multiply(x1, x2)
array([[ 0., 1., 4.], [ 0., 4., 10.], [ 0., 7., 16.]])
Example 3: Performing multiplication using “*” operator
We can also perform multiplication operation by using ‘*’ operator, apart from using numpy multiply()
a = np.array([8,3])
a
array([8, 3])
b = np.array([2,17])
b
array([ 2, 17])
a * b
array([16, 51])
It’s time to understand how dot operations are executed using numpy
Numpy Dot : np.dot()
The numpy.dot() operation helps in executing dot operations. It can help in performing various kinds of dot operations.
Syntax
numpy.dot(a, b, out=None)
a : array_like – This argument provides the first array for the dot operations to execute.
b : array_like – This argument provides the second array for the dot operations to execute.
out : ndarray (optional) – Output argument. This must have the exact kind that would be returned if it was not used.
It also has the feature of raising value error if the last dimension of a is not the same size as the second-to-last dimension of b.
Example 1: Using Single Dimension Array
Here in this first example, the two values are provided.
np.dot(3, 4)
12
Example 2: Using 2-Dimensional Array
a = [[1, 0], [0, 1]]
a
[[1, 0], [0, 1]]
b = [[4, 1], [2, 2]]
b
[[4, 1], [2, 2]]
np.dot(a, b)
array([[4, 1], [2, 2]])
Lastly, we have the divide mathematical operation using numpy
Numpy Divide : np.divide()
The divide operation is performed through np.divide() function. This division function Returns a true division of the inputs, element-wise.
Instead of the Python traditional ‘floor division’, this returns a true division. True division adjusts the output type to present the best answer, regardless of input types.
Syntax
numpy.divide(x1, x2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj])
x1 : array_like – This argument provides the dividend array.
x2 : array_like – This argument is Divisor array. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None (optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.
where : array_like – (optional) – This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value.
kwargs – This parameter is used for other keyword arguments
The floor division operator // was added in Python 2.2 making // and / equivalent operators. The default floor division operation of / can be replaced by true division with from future import division.
In Python 3.0, // is the floor division operator and / the true division operator. The true_divide(x1, x2) function is equivalent to true division in Python.
Example 1 : Using true_divide() function for obtaining results as float values
x = np.arange(15)
x
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
np.true_divide(x,4)
array([0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. , 2.25, 2.5 , 2.75, 3. , 3.25, 3.5 ])
np.divide(x,4)
array([0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. , 2.25, 2.5 , 2.75, 3. , 3.25, 3.5 ])
Here true_divide() and divide function produces same results, divide() function was used in previous versions of python. From 3.0 python version, we use true_divide() to get float results.
Example 2: Obtaining float values as results i.e. true division results using ‘ / ‘
from __future__ import division
x = np.arange(20)
x/4
array([0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. , 2.25, 2.5 , 2.75, 3. , 3.25, 3.5 , 3.75, 4. , 4.25, 4.5 , 4.75])
Example 3: Obtaining whole numbers as results i.e. floor division results using double slash symbol
x//4
array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4], dtype=int32)
Conclusion
Reaching the last stage of this article, we have learned about the syntax of np.sum(), np.subtract(), np.multiply(), np.dot() and np.divide() functions which are helpful in executing basic mathematical operations with the help of numpy. We also understood how we can use these functions like numpy sum, numpy subtract, numpy multiply, numpy dot and numpy divide with different examples.
Click Here To Download This Tutorial in Interactive Jupyter Notebook
- Also Read – Python Numpy Array – A Gentle Introduction to beginners
- Also Read – Tutorial – numpy.arange() , numpy.linspace() , numpy.logspace() in Python
- Also Read – Complete Numpy Random Tutorial – Rand, Randn, Randint, Normal
- Also Read – Tutorial – Numpy Shape, Numpy Reshape and Numpy Transpose in Python
Reference- https://numpy.org/doc/