The Python library NumPy
has the methods sum()
and product()
, which can be used to find the sum and product of array elements.
numpy.sum()
methodnumpy.sum(arr, axis=None, dtype=None, out=None)
The numpy.sum()
method returns the sum of elements in a given input array over a specified axis.
numpy.prod()
methodnumpy.prod(arr, axis=None, dtype=None, out=None)
The numpy.prod()
method returns the product of elements in a given input array over a specified axis.
Note: A 2-D array can be created using a list of lists in Python.
arr
: This is an array_like
object that represents the input data.axis
: This is an optional parameter. It represents the axes along which the operation is to be performed.dtype
: This is an optional parameter. It represents the return type of the array.out
: This is an optional parameter. It represents the alternative output array in which the result is to be placed.Note: If the
out
parameter is specified, it returns an array reference toout
.
The following code snippets show how to find the sum and product of the 2-D array using the numpy.sum()
and numpy.prod()
methods.
Find the sum of a 2-D array using the numpy.sum()
method.
# import numpy import numpy as np # create a list my_list1 = [24,8,3,4,34,8] my_list2 = [5,7,2,10,15,7] # convert to a numpy 2D array np_list = np.array([my_list1, my_list2]) # compute the sum of array elements and store it np_list_sum = np.sum(np_list, axis=0) print(np_list_sum)
numpy
library.my_list1
and my_list2
.np_list
.np.sum()
to compute the sum of elements in the np_list
.Find the product of a 2-D array using the numpy.product()
method.
# import numpy import numpy as np # create a list my_list1 = [24,8,3,4,8] my_list2 = [5,7,2,10,7] # convert to a numpy 2D array np_list = np.array([my_list1, my_list2]) # compute the product of 2D array # and store the result in np_list_cumprod np_list_prod = np.prod(np_list, axis=0) print(np_list_prod)
numpy
library.my_list1
and my_list2
.np_list
.np.prod()
to compute the product of elements in the np_list
.RELATED TAGS
CONTRIBUTOR
View all Courses