Home > Back-end >  How to delete zeroes in the upper triangular part of a matrix with numpy
How to delete zeroes in the upper triangular part of a matrix with numpy

Time:01-21

I have a matrix 'A' with shape(68,68) and its upper triangle has only zeroes in it. The lower triangle has the values I'm interested in. For instance:

>>> A
array([[ 0,  0,  0],
       [ 1,  0,  0],
       [ 2,  3,  0],
       [ 4,  5,  6]])

How can I obtain a matrix 'B' with no values in the upper triangle, like this:

>>> B
array([[  ,   ,  ],
       [ 1,   ,  ],
       [ 2,  3,  ],
       [ 4,  5, 6]])

CodePudding user response:

There isn't really a representation for "no value" in numpy, at least not in the way that you explained.

The closest you can get is probably np.nan, which is a commonly-used representation of "not a number".

np.nan is treated as a number in the sense that it doesn't break any code that tries to work mathematically with it, but it's not considered to be zero either because any operation done with it results in a np.nan. For example:

import numpy as np

>>> 0   10  
# output: 10

>>> np.nan   10
# output: nan 

In your case, replacing the upper triangular part of A with np.nan effectively means "ignore this part in any operations done with A".

As to how to replace the values with np.nans, you can do:

import numpy as np

A = np.array([
    [ 0,  0,  0],
    [ 1,  0,  0],
    [ 2,  3,  0],
    [ 4,  5,  6],
])

A = A.astype(float)
A[A == 0] = np.nan

print(A)

Output:

[[nan nan nan]
 [ 1. nan nan]
 [ 2.  3. nan]
 [ 4.  5.  6.]]

Note that we had to convert A from an integer matrix to a float matrix, since np.nans are technically considered to be floats.

  • Related