Absolute sum of elements in Numpy matrix

Get FREE domain for 1st year and build your brand new site

Binary Tree book

In this article, we have explained how to find the Absolute sum of elements in Numpy matrix with complete Python code example.

Table of contents:

  1. Absolute sum of elements in Numpy matrix
  2. Normal Sum
  3. Conclusion

Absolute sum of elements in Numpy matrix

Absolute sum of elements in Numpy matrix

To find the Absolute sum of elements in Numpy matrix, we need to follow to steps:

  • Get absolute value of elements in Numpy matrix (using np.abs)
  • Find sum of elements of updated matrix (using np.nansum)

The code snippet is as follows:

abs_matrix = np.abs(matrix)
abs_sum = np.nansum(abs_matrix, dtype=np.float64)

Note:

  • dtype is the data type of the sum output. We have set it to float 64 bits to avoid overflow.
  • abs_matrix has the absolute value of all elements in the original matrix.
  • nansum gives the sum of all elements in abs_matrix where there is no negative element. nansum will avoid nan values in the matrix.

The complete Python code example is as follows:

import numpy as np
matrix = np.array([[1.94353, -2.13254, 3.00845], [-4.3423, 5.5675, -6.01029]])
print ("Original matrix = ")
print (matrix)

abs_matrix = np.abs(matrix)
abs_sum = np.nansum(abs_matrix, dtype=np.float64)
print ("Absolute sum = ")
print (abs_sum)

Output:

Original matrix = 
[[ 1.94353 -2.13254  3.00845]
 [-4.3423   5.5675  -6.01029]]

Absolute sum = 
23.00461

Normal Sum

Now, the difference between absolute sum and normal sum is critical for several data as in normal sum, negative and positive numbers tend to cancel each other.

When you are using sum as a metric to compare Numpy data/ matrix, it is important to use absolute sum.

The complete Python code example is as follows:

import numpy as np
matrix = np.array([[1.94353, -2.13254, 3.00845], [-4.3423, 5.5675, -6.01029]])
print ("Original matrix = ")
print (matrix)

sum = np.nansum(matrix, dtype=np.float64)
print ("Sum = ")
print (sum)

Output:

Original matrix = 
[[ 1.94353 -2.13254  3.00845]
 [-4.3423   5.5675  -6.01029]]

Sum = 
-1.965650000000001

Note:

  • The absolute sum is 23.00461
  • The normal sum is -1.965650000000001
  • The difference between the two values is significant.

Conclusion

With this article at OpenGenus, you must have the complete idea of how to get the absolute sum of a Numpy matrix easily with just two code lines.