Multiple snippets in list indexing for numpy array

The Numpy array allows a list of indexes, e.g.

a = np.arange(1000) l = list([1,44,66,33,90,345]) a[l] = 22 

But this method does not work if we want, for example, to use indexing or indexes with several fragments, as well as a slice.

 a = np.arange(1000) l = list([1,44,66,33,90, slice(200,300) , slice(500,600) ]) a[l] = 22 

This code returns an error message:

 IndexError: too many indices 

My question is very simple: did you know that in numpy or scipy there is an effective method for using this kind of indexing?

Or what a good and effective way to use this indexing method?

Remember that using slices creates very fast code; and my problem is to have the code as fast as possible.

+5
python arrays numpy indexing
source share
2 answers

What comes to my mind:

 a = np.arange(1000) l = np.hstack(([1, 44, 66, 33, 90], np.arange(200, 300), np.arange(500, 600))) a[l] = 22 

I'm not sure if this is the easiest way, but it works.

Edit: you are right that this is slower than using slices; but you cannot create a slice object with arbitrary values. Perhaps you just need to complete a few tasks:

 %timeit a[np.hstack(([1, 44, 66, 33, 90], np.arange(200, 300), np.arange(500, 600)))] = 22 10000 loops, best of 3: 39.5 us per loop %timeit a[[1, 44, 66, 33, 90]] = 22; a[200:300] = 22; a[500:600] = 22 100000 loops, best of 3: 18.4 us per loop 
+4
source share

You can use fancy indexing to create a list of indexes.

 l = numpy.array([1,44,66,33,90]+range(200,300)+range(500,600)) a[l] = 22 

But as @Lev noted, this may not be so fast (although it will almost certainly be if you can pre-copy the index list).

However, bizarre indexing is applied along the axis. So you can imagine the index on one axis and cut the rest, if that helps at all:

 a = numpy.random.randn(4, 5, 6) l = numpy.array([1, 2]) a[l, slice(None), slice(2, 4)] = 10 
0
source share

All Articles