pythonic array subsetting

Robert Kern robert.kern at
Tue Feb 17 22:17:00 CET 2009

On 2009-02-17 14:36, Nick Matzke wrote:
> Looks like "compress" is the right numpy function, but it took forever
> for me to find it...
> x = array([[1,2,3], [4,5,6], [7,8,9]], dtype=float)
> compress([1,2], x, axis=1)
> result:
> array([[ 1., 2.],
> [ 4., 5.],
> [ 7., 8.]])

No, that's actually not correct. compress() takes a boolean mask, not integer 
indices. It just happens to be the case that compress() implicitly appends 
Falses to the end if the lengths don't match. Also, numpy indices are 0-indexed 
just like most Python sequences.

If you need to specify integer indices, you need this:

In [4]: x[:,[0,1]]
array([[ 1.,  2.],
        [ 4.,  5.],
        [ 7.,  8.]])

If you have more numpy questions, you should ask on the numpy mailing list.

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

More information about the Python-list mailing list