Numpy array index handling

Robert Kern robert.kern at gmail.com
Fri Jul 13 15:08:11 EDT 2007


phishboh at gmail.com wrote:
> Being a Matlab user wanting to switch to Python/SciPy,

Fantastic! You might be interested in joining the numpy mailing list. There are
a lot more of us numpy devs and users there than here.

  http://www.scipy.org/Mailing_Lists

> I'd like to
> know how the following Matlab code would be written in Python:
> 
> % First, just some artificial data
> N = 1000000 ;
> input = sign(randn(1, N)) ;
> a = (1 : N) ;
> % This is what I'd like to do;
> % for indices where the input has a certain value, compute and store
> something
> % for indices where the input has another certain value, compute and
> store something else
> output(input < 0) = 10 * a(input < 0) ;
> output(input > 0) = 20 * a(input > 0) ;
> 
> I have tried the following in Python:
> N = 1000000
> input = sign(randn(N))
> a = arange(N)
> output = zeros(N)
> output[input < 0] = 10 * a[input < 0]
> output[input > 0] = 20 * a[input > 0]
> 
> However, that gives me in IndexError.

When reporting that you get an error, copy-and-pasting the full traceback is
highly recommended. We can give you an answer much more quickly if you do. In
this case, your example works fine for me with numpy 1.0.3 (after supplying the
missing imports).


In [1]: from numpy import *

In [2]: N = 1000000

In [3]: input = sign(random.randn(N))

In [4]: a = arange(N)

In [5]: output = zeros(N)

In [6]: output[input < 0] = 10 * a[input < 0]

In [7]: output[input > 0] = 20 * a[input > 0]


If you are still having problems, please join us on numpy-discussion with the
full traceback.

-- 
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