[Numpy-discussion] np.take versus fancy indexing

Eric Firing efiring@hawaii....
Mon Sep 21 12:30:38 CDT 2009


Wes McKinney wrote:
> Any clue why I'm seeing this behavior? np.take's documentation says it
> does the "same thing" as fancy indexing, but from this example I'm not
> so sure:

The code used to implement np.take is not the same as that used in fancy 
indexing.  np.take's mission is simpler, so it uses type-specific code 
for each numeric type, generated using a template.  The same type of 
optimization was done for putmask and clip.  I haven't looked into the 
code used by fancy indexing.  Presumably it could be sped up by using 
np.take (or the strategy used by np.take) in suitable cases, but I 
suspect that would be a big job, with plenty of opportunities for 
introducing bugs.

Eric

> 
> import numpy as np
> 
> mat = np.random.randn(5000, 1000)
> selector = np.array(np.arange(5000)[::2])
> 
> In [95]: timeit submat = mat[selector]
> 10 loops, best of 3: 68.4 ms per loop
> 
> In [96]: timeit submat = np.take(mat, selector, axis=0)
> 10 loops, best of 3: 21.5 ms per loop
> 
> indeed the result is the same:
> 
> In [97]: (mat[selector] == np.take(mat, selector, axis=0)).all()
> Out[97]: True
> 
> In [98]: mat[selector].flags
> Out[98]:
>   C_CONTIGUOUS : True
>   F_CONTIGUOUS : False
>   OWNDATA : True
>   WRITEABLE : True
>   ALIGNED : True
>   UPDATEIFCOPY : False
> 
> In [99]: np.take(mat, selector, axis=0).flags
> Out[99]:
>   C_CONTIGUOUS : True
>   F_CONTIGUOUS : False
>   OWNDATA : True
>   WRITEABLE : True
>   ALIGNED : True
>   UPDATEIFCOPY : False
> 
> What's going on here / am I doing something wrong?
> 
> Thanks,
> Wes
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion



More information about the NumPy-Discussion mailing list