Reputation: 750
I have a numpy array looking like this:
a = np.array([[0.87, 1.10, 2.01, 0.81 , 0.64, 0. ],
[0.87, 1.10, 2.01, 0.81 , 0.64, 0. ],
[0.87, 1.10, 2.01, 0.81 , 0.64, 0. ],
[0.87, 1.10, 2.01, 0.81 , 0.64, 0. ],
[0.87, 1.10, 2.01, 0.81 , 0.64, 0. ],
[0.87, 1.10, 2.01, 0.81 , 0.64, 0. ]])
I like to manipulate this by setting the 'bottom left' part to zero. Instead of looping through rows and columns, I want to achieve this by means of indexing:
ix = np.array([[1, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1],
[0, 0, 1, 1, 1, 1],
[0, 0, 0, 1, 1, 1],
[0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 1]])
However a[ix]
does not deliver what I expect, as a[ix].shape
is now (6,6,6)
, i.e. a new dimension has been added. What do I need to do in order to preserve the shape of a
, but with all zeros in the bottom left?
Upvotes: 1
Views: 71
Reputation: 51155
If you don't want to have to worry about creating ix
at all, what you're really asking for is the upper triangle of a
, which is the method numpy.triu
np.triu(a)
array([[0.87, 1.1 , 2.01, 0.81, 0.64, 0. ],
[0. , 1.1 , 2.01, 0.81, 0.64, 0. ],
[0. , 0. , 2.01, 0.81, 0.64, 0. ],
[0. , 0. , 0. , 0.81, 0.64, 0. ],
[0. , 0. , 0. , 0. , 0.64, 0. ],
[0. , 0. , 0. , 0. , 0. , 0. ]])
Upvotes: 1
Reputation: 214967
You don't need advanced indexing for this purpose. Boolean indexing would be more suitable with what you have:
a[~ix.astype(bool)] = 0
a
#array([[ 0.87, 1.1 , 2.01, 0.81, 0.64, 0. ],
# [ 0. , 1.1 , 2.01, 0.81, 0.64, 0. ],
# [ 0. , 0. , 2.01, 0.81, 0.64, 0. ],
# [ 0. , 0. , 0. , 0.81, 0.64, 0. ],
# [ 0. , 0. , 0. , 0. , 0.64, 0. ],
# [ 0. , 0. , 0. , 0. , 0. , 0. ]])
Upvotes: 1