Np.sum trong python

axis parameter is optional and is used to specify the axis along which we want to perform addition. When you do not provide axis parameter value to np.sum() function then it adds all the values together and produces a single value.

dtype parameter controls the data type of the resultant sum.

Python program using np.sum() on 1-Dimensional Numpy Array

import numpy as np

a = np.array([32, 4, 8, 12, 20])
print('Sum of arr is ', np.sum(a))

Output of the above program

Sum of arr is 76

As you can see in the above output, np.sum() has added all the values. In 1-dimensional array, it is optional to provide axis parameter to sum() function.

NumPy sum() function in python is used to return the sum/total of all elements over a given array. This function takes several arguments, among use


# Syntax of sum()
numpy.sum(array, axis=None, dtype=None, out=None, keepdims=, initial=)
0 argument to specify the returned data type and use the

# Syntax of sum()
numpy.sum(array, axis=None, dtype=None, out=None, keepdims=, initial=)
1 argument to specify the initial value to consider for the sum.

Using this function you can do the following.

  • Get the sum of all array elements of the given array,
  • Get the sum of each row over a specified axis, and
  • Get the sum of each column of a given array.

In this article, I will explain the syntax of numpy sum() function, the different arguments it takes, and its usage by examples like how to calculate the sum values of the given array. For more examples of NumPy, refer to NumPy Tutorial

1. Quick Examples of NumPy Sum Function

If you are in a hurry, below are some quick examples of how to use NumPy sum() function.


# Below are the quick examples

# Example 1: # Create a numpy array
# Get the sum of an array 
arr = np.array([14, 17, 19, 22])
sum = np.sum(arr)

# Example 2: Create 2-D numpy array
# Get the Sum of all the elements in an array            
arr = np.array([[12, 14], [17, 19],[13, 16],[24, 27]])
sum = np.sum(arr)

# Example 3: Get the sum of each column element along axis = 0
sum = np.sum(arr, axis=0)

# Example 4: Get the sum of each row element along axis = 1
sum = np.sum(arr, axis=1)

# Example 5: Get the sum of an array to specify data type 
sum = np.sum(arr, axis=1, dtype=float)

# Example 6: Specify an initial value for the sum
sum = np.sum(arr, axis=1, initial=15)

# Example 7: Get the sum using nansum()
arr = np.array([[2, 3], [4, np.nan]])
arr1 = np.nansum(arr)

2. Syntax of sum()

The following is the syntax of the sum() function.


# Syntax of sum()
numpy.sum(array, axis=None, dtype=None, out=None, keepdims=, initial=)

2.1 Parameters of sum()

Below are the parameters of the sum() function.

  • 
    # Syntax of sum()
    numpy.sum(array, axis=None, dtype=None, out=None, keepdims=, initial=)
    
    2 – Input array, in which the elements to be calculated as a sum.
  • 
    # Syntax of sum()
    numpy.sum(array, axis=None, dtype=None, out=None, keepdims=, initial=)
    
    3 – Axis or axes along which a sum is performed. The default, axis=None, it sums all of the elements of the input array. If the axis is negative the counts start from the last to the first axis. axis = 0 means along the column and axis = 1 means working along the row.
  • 
    # Syntax of sum()
    numpy.sum(array, axis=None, dtype=None, out=None, keepdims=, initial=)
    
    0 – You can use dtype to specify the returned output data type.
  • 
    # Syntax of sum()
    numpy.sum(array, axis=None, dtype=None, out=None, keepdims=, initial=)
    
    5 – Alternative output array in which to place the result. The array must have the same dimensions as the expected output. Default is None.
  • 
    # Syntax of sum()
    numpy.sum(array, axis=None, dtype=None, out=None, keepdims=, initial=)
    
    6 – The keepdims is a boolean parameter. If this is set to True, the axes which are reduced are left in the result as dimensions with size one.
  • 
    # Syntax of sum()
    numpy.sum(array, axis=None, dtype=None, out=None, keepdims=, initial=)
    
    1 – The initial parameter provides the Starting value for the sum.

2.2 Return Value of sum()

It returns an array, it contains the sum of elements of the input array along with the specified axis. If the axis = None then it will return a scalar value.

3. Usage of NumPy sum() Function

The sum() function in NumPy package of Python is used to calculate the total of all elements, the total of each row, and the total of each column of a given array.

3.1 Get the Sum of 1-D Array

Let’s see how to calculate the sum of all elements of the 1-dimensional array, In order to do so first, let’s initialize the 1-D NumPy array using


# Syntax of sum()
numpy.sum(array, axis=None, dtype=None, out=None, keepdims=, initial=)
8 and pass this array as input to the sum().


import numpy as np

# Create a numpy array
arr = np.array([14, 17, 19, 22])

# Get the sum of an array 
sum = np.sum(arr)
print(sum)

# Output
# 72

3.2 Get the Sum of 2-D Array

Let’s compute the sum of all the elements of the 2-D array. When using the 2-D array, it considers all values in the array to calculate the sum and returns a scalar value. It considers


# Syntax of sum()
numpy.sum(array, axis=None, dtype=None, out=None, keepdims=, initial=)
9 by default. Note that it doesn’t calculate the sum of each row or the sum of each column instead calculates the sum of all values.


# Create 2-D numpy array
arr = np.array([[12, 14], [17, 19],[13, 16],[24, 27]])

# Get the Sum of all the elements in an array            
sum = np.sum(arr)
print("Sum of all the elements is :", sum)

# Output
# Sum of all the elements is : 142

4. Get the Sum of Each Column of 2-D Array

In order to calculate the sum for each column of NumPy array, specify the


import numpy as np

# Create a numpy array
arr = np.array([14, 17, 19, 22])

# Get the sum of an array 
sum = np.sum(arr)
print(sum)

# Output
# 72
0 . This gets you to sum along the column axis when you have a 2-dimensional array. This returns the ndarray of size equal to the number of columns in your array.


# Get the sum of each column element along axis = 0
sum = np.sum(arr, axis=0)
print(sum)

# Output
# [66 76]

5 Get the Sum of Each Row of 2-D Array

Similarly, to calculate the sum for each row, specify the


import numpy as np

# Create a numpy array
arr = np.array([14, 17, 19, 22])

# Get the sum of an array 
sum = np.sum(arr)
print(sum)

# Output
# 72
1. This gets you to sum along the rows axis. This returns the ndarray of size equal to the number of rows in your array.


# Get the sum of each row element along axis = 1
sum = np.sum(arr, axis=1)
print(sum)

# Output
# [26 36 29 51]

6. Specify the Type of the Return Value

By default, the return type of NumPy sum() will be equal to the type of your input array elements. In our above examples, we have arrays of type


import numpy as np

# Create a numpy array
arr = np.array([14, 17, 19, 22])

# Get the sum of an array 
sum = np.sum(arr)
print(sum)

# Output
# 72
3 hence, the result is also in int type. Let’s change this by specifying the dtype argument. Using this argument you can specify the return type of the sum() function.

The following example calculates the sum for each row and returns the sum in float type.


# Get the sum of an array to specify data type 
sum = np.sum(arr, axis=1, dtype=float)
print(sum)

# OutPut
# [26. 36. 29. 51.]

7. Consider Initial Value to NumPy sum()

You can also start the sum with an initial value other than zero by using the


# Syntax of sum()
numpy.sum(array, axis=None, dtype=None, out=None, keepdims=, initial=)
1 argument. When used

# Syntax of sum()
numpy.sum(array, axis=None, dtype=None, out=None, keepdims=, initial=)
1 argument, the sum() starts with this initial value and adds all elements to it to get the final sum/total value.


# Specify an initial value for the sum
sum = np.sum(arr, axis=1, initial=15)
print(sum)

# Output
# [41 51 44 66]

8. Get the Sum using np.NaN

If you have


import numpy as np

# Create a numpy array
arr = np.array([14, 17, 19, 22])

# Get the sum of an array 
sum = np.sum(arr)
print(sum)

# Output
# 72
6 values in your array, applying the sum() function results in

import numpy as np

# Create a numpy array
arr = np.array([14, 17, 19, 22])

# Get the sum of an array 
sum = np.sum(arr)
print(sum)

# Output
# 72
7 output. To overcome this use

import numpy as np

# Create a numpy array
arr = np.array([14, 17, 19, 22])

# Get the sum of an array 
sum = np.sum(arr)
print(sum)

# Output
# 72
8 function, nansum() is used to calculate the sum of the array ignoring the nan values. This function is also used to sum all elements, the sum of each row, and the sum of each column of a given array by ignoring NaN values.


# Get the sum using nansum()
arr = np.array([[2, 3], [4, np.nan]])
arr1 = np.nansum(arr)
print(arr1)

# Output :
# 9.0

7. Conclusion

In this article, I have explained how to use the Python NumPy sum function(). Use this function to compute the sum of the array elements along with specified axis, datatype, and initial value with examples. And also learn what happens if you have NaN values in the array and how to overcome this by using nansum() function.