pythonpython-3.xnumpynumpy-indexing

Numpy advanced indexing fails


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?


Solution

  • 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.  ]])