Find the sum and product of a NumPy array elements - GeeksforGeeks

14 Dec, 2021
In this article, let’s discuss how to find the sum and product of NumPy arrays. 
Sum of NumPy array elements can be achieved in the following ways
Method #1:  Using numpy.sum()
Syntax: numpy.sum(array_name, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
Example:
Python3
# importing numpyimport numpy as np  def main():     # initialising array    print('Initialised array')    gfg = np.array([[1, 2, 3], [4, 5, 6]])    print(gfg)         # sum along row    print(np.sum(gfg, axis=1))         # sum along column    print(np.sum(gfg, axis=0))         # sum of entire array    print(np.sum(gfg))         # use of out    # initialise a array with same dimensions    # of expected output to use OUT parameter    b = np.array([0])  # np.int32)#.shape = 1    print(np.sum(gfg, axis=1, out=b))         # the output is stored in b    print(b)         # use of keepdim    print('with axis parameter')         # output array's dimension is same as specified    # by the axis    print(np.sum(gfg, axis=0, keepdims=True))         # output consist of 3 columns    print(np.sum(gfg, axis=1, keepdims=True))         # output consist of 2 rows    print('without axis parameter')    print(np.sum(gfg, keepdims=True))         # we added 100 to the actual result    print('using initial parameter in sum function')    print(np.sum(gfg, initial=100))     # False allowed to skip sum operation on column 1 and 2    # that's why output is 0 for them    print('using where parameter ')    print(np.sum(gfg, axis=0, where=[True, False, False]))  if __name__ == "__main__":    main()
Output:
Initialised array
[[1 2 3]
 [4 5 6]]
[ 6 15]
[5 7 9]
21
[21]
[21]
with axis parameter
[[5 7 9]]
[[ 6]
 [15]]
without axis parameter
[[21]]
using initial parameter in sum function
121
using where parameter 
[5 0 0]
Note: using numpy.sum on array elements consisting Not a Number (NaNs) elements gives an error, To avoid this we use numpy.nansum() the parameters are similar to the former except the latter doesn’t support where and initial.
Method #2: Using numpy.cumsum()
Returns the cumulative sum of the elements in the given array.
Syntax: numpy.cumsum(array_name, axis=None, dtype=None, out=None)
Example:
Python3
# importing numpyimport numpy as np  def main():     # initialising array    print('Initialised array')    gfg = np.array([[1, 2, 3], [4, 5, 6]])         print('original array')    print(gfg)         # cumulative sum of the array    print(np.cumsum(gfg))         # cumulative sum of the array along    # axis 1    print(np.cumsum(gfg, axis=1))         # initialising a 2x3 shape array    b = np.array([[None, None, None], [None, None, None]])         # finding cumsum and storing it in array    np.cumsum(gfg, axis=1, out=b)         # printing resultant array    print(b)  if __name__ == "__main__":    main()
Output:
Initialised array
original array
[[1 2 3]
 [4 5 6]]
[ 1  3  6 10 15 21]
[[ 1  3  6]
 [ 4  9 15]]
[[1 3 6]
 [4 9 15]]
Product of NumPy arrays can be achieved in the following ways 
Method #1:  Using numpy.prod()
Syntax: numpy.prod(array_name, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
Example:
Python3
# importing numpyimport numpy as np def main():     # initialising array    print('Initialised array')    gfg = np.array([[1, 2, 3], [4, 5, 6]])    print(gfg)         # product along row    print(np.prod(gfg, axis=1))         # product along column    print(np.prod(gfg, axis=0))         # sum of entire array    print(np.prod(gfg))         # use of out    # initialise a array with same dimensions    # of expected output to use OUT parameter    b = np.array([0])  # np.int32)#.shape = 1    print(np.prod(gfg, axis=1, out=b))         # the output is stored in b    print(b)         # use of keepdim    print('with axis parameter')         # output array's dimension is same as specified    # by the axis    print(np.prod(gfg, axis=0, keepdims=True))         # output consist of 3 columns    print(np.prod(gfg, axis=1, keepdims=True))         # output consist of 2 rows    print('without axis parameter')    print(np.prod(gfg, keepdims=True))         # we initialise product to a factor of 10    # instead of 1    print('using initial parameter in sum function')    print(np.prod(gfg, initial=10))         # False allowed to skip sum operation on column 1 and 2    # that's why output is 1 which is default initial value    print('using where parameter ')    print(np.prod(gfg, axis=0, where=[True, False, False]))     if __name__ == "__main__":    main()
Output:
Initialised array
[[1 2 3]
 [4 5 6]]
[  6 120]
[ 4 10 18]
720
[720]
[720]
with axis parameter
[[ 4 10 18]]
[[  6]
 [120]]
without axis parameter
[[720]]
using initial parameter in sum function
7200
using where parameter 
[4 1 1]
Method #2:  Using numpy.cumprod()
Returns a cumulative product of the array.
Syntax: numpy.cumsum(array_name, axis=None, dtype=None, out=None)axis = [integer,Optional]
Python3
# importing numpyimport numpy as np  def main():     # initialising array    print('Initialised array')    gfg = np.array([[1, 2, 3], [4, 5, 6]])    print('original array')    print(gfg)         # cumulative product of the array    print(np.cumprod(gfg))         # cumulative product of the array along    # axis 1    print(np.cumprod(gfg, axis=1))         # initialising a 2x3 shape array    b = np.array([[None, None, None], [None, None, None]])         # finding cumprod and storing it in array    np.cumprod(gfg, axis=1, out=b)         # printing resultant array    print(b)  if __name__ == "__main__":    main()
Output:
Initialised array
original array
[[1 2 3]
 [4 5 6]]
[  1   2   6  24 120 720]
[[  1   2   6]
 [  4  20 120]]
[[1 2 6]
 [4 20 120]]
anikakapoor
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Bar Plot in Matplotlib