Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Numpy exercise
  • pandas
  • Matplotlib
  • Data visulisation
  • EDA
  • Machin Learning
  • Deep Learning
  • NLP
  • Data science
  • ML Tutorial
  • Computer Vision
  • ML project
Open In App
Next Article:
Minimum steps to make sum and the product of all elements of array non-zero
Next article icon

Find the sum and product of a NumPy array elements

Last Updated : 14 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, let’s discuss how to find the sum and product of NumPy arrays. 

Sum of the NumPy array

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 numpy
import 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 numpy
import 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 the NumPy array

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 numpy
import 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 numpy
import 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]]


Next Article
Minimum steps to make sum and the product of all elements of array non-zero

T

technikue20
Improve
Article Tags :
  • Python
  • Python numpy-arrayManipulation
  • Python-numpy
Practice Tags :
  • python

Similar Reads

  • Minimum steps to make sum and the product of all elements of array non-zero
    Given an array arr of N integers, the task is to find the minimum steps in which the sum and product of all elements of the array can be made non-zero. In one step any element of the array can be incremented by 1.Examples: Input: N = 4, arr[] = {0, 1, 2, 3} Output: 1 Explanation: As product of all e
    7 min read
  • Calculate the sum of all columns in a 2D NumPy array
    Let us see how to calculate the sum of all the columns in a 2D NumPy array.Method 1 : Using a nested loop to access the array elements column-wise and then storing their sum in a variable and then printing it.Example 1:   [GFGTABS] Python3 # importing required libraries import numpy # explicit funct
    3 min read
  • Generate a matrix product of two NumPy arrays
    We can multiply two matrices with the function np.matmul(a,b). When we multiply two arrays of order (m*n) and  (p*q ) in order to obtained matrix product then its output contains m rows and q columns where n is n==p is a necessary condition. Syntax: numpy.matmul(x1, x2, /, out=None, *, casting='same
    2 min read
  • Find indices of elements equal to zero in a NumPy array
    Sometimes we need to find out the indices of all null elements in the array. Numpy provides many functions to compute indices of all null elements.  Method 1: Finding indices of null elements using numpy.where() This function returns the indices of elements in an input array where the given conditio
    3 min read
  • NumPy| How to get the unique elements of an Array
    To find unique elements of an array we use the numpy.unique() method of the NumPy library in Python. It returns unique elements in a new sorted array. Example: [GFGTABS] Python3 import numpy as np arr = np.array([1, 2, 3, 1, 4, 5, 2, 5]) unique_elements = np.unique(arr) print(unique_elements) [/GFGT
    2 min read
  • Calculate the sum of the diagonal elements of a NumPy array
    Sometimes we need to find the sum of the Upper right, Upper left, Lower right, or lower left diagonal elements. Numpy provides us the facility to compute the sum of different diagonals elements using numpy.trace() and numpy.diagonal() method. Method 1: Finding the sum of diagonal elements using nump
    2 min read
  • Calculating the sum of all columns of a 2D NumPy array
    Let us see how to calculate the sum of all the columns of a 2 dimensional NumPy array. Example : Input : [[1, 2, 3, 4, 5], [5, 6, 7, 8, 9], [2, 1, 5, 7, 8], [2, 9, 3, 1, 0]] Output : [10, 18, 18, 20, 22] Input : [[5, 4, 1, 7], [0, 9, 3, 5], [3, 2, 8, 6]] Output : [8, 15, 12, 18] Approach 1 : We will
    2 min read
  • NumPy | Get the Powers of Array Values Element-Wise
    To calculate the power of elements in an array we use the numpy.power() method of NumPy library. It raises the values of the first array to the powers in the second array. Example:[GFGTABS] Python3 import numpy as np # creating the array sample_array1 = np.arange(5) sample_array2 = np.arange(0, 10,
    3 min read
  • Appending values at the end of an NumPy array
    Let us see how to append values at the end of a NumPy array. Adding values at the end of the array is a necessary task especially when the data is not fixed and is prone to change. For this task, we can use numpy.append() and numpy.concatenate(). This function can help us to append a single value as
    4 min read
  • Products of Vectors and Matrices in NumPy
    Working with vector and matrix operations is a fundamental part of scientific computing and data analysis. NumPy is a Python library that computes various types of vector and matrix products. Let's discuss how to find the inner, outer and cross products of matrices and vectors using NumPy in Python.
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences