NumPy Sum

In this tutorial you will learn:

  • What is difference between summation and addition?
  • Implementation of summation using different functions in Python
  • Python Syntax

Summation

Summation is the sum of all the elements of an array, if we are adding up two arrays it would be the index wise addition of elements which will result in another array having the size equal to the size of arrays being added up. Summation and addition are commonly used in mathematics and sciences to carry out basic tasks. Summation is mostly carried out on more than one elements which are contained in some data structures like list, tuple, array etc and it produces a single value.

Implementation of Summation

Inorder to enhance the understanding, we will first see the result of adding up two 1D arrays having size 4, here you can observe that the result produced is an array having index wise addition.
  1. #importing the NumPy library
  2. import numpy as np
  3. #declaring a first array
  4. arr_1= np.array([1,2,3,4])
  5. print('1st array being added up:',arr_1)
  6. #declaring a second array
  7. arr_2=np.array([5,6,7,8])
  8. print('2nd array being added up:',arr_2)
  9. #adding up array using add() function
  10. res = np.add(arr_1,arr_2)
  11. #printing the result
  12. print('Printing the result of add() function:', res)
In this example we will be summing up the content of one array, here you can observe that the result of applying sum() on an array is the sum of all its elements.
  1. #importing the NumPy library
  2. import numpy as np
  3. #declaring an array
  4. arr_1= np.array([1,2,3,4])
  5. print('Array being summed up:', arr_1)
  6. #summing up the contents of an array
  7. res = np.sum(arr_1)
  8. #printing the result
  9. print('The result of sum() function:', res)
NumPy provides another function ‘cumsum()’, the function takes in an array and at each index gives out a cumulative sum after adding up all the elements of the lower indexes of the array.
  1. #importing the NumPy library
  2. import numpy as np
  3. #declaring an array
  4. arr= np.array([10,20,30,40])
  5. print('Array being cummulative summed:', arr)
  6. #summing up the contents of an array
  7. res = np.cumsum(arr)
  8. #printing the result
  9. print('The result of cumsum() function:', res)

Add new comment