Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple slice in list indexing for numpy array

Numpy array admits a list of indices, for example

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

But this method don't work if we want to use a multiple slice indexing or indices plus a slice, for example.

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: do you know if in numpy or scipy there exist an efficient method for using this kind of indexing?

Or what's a good and efficient way for using an indexing method like this?

Don't forget that the usage of slices produce a very fast code; and my problem is to have as faster as possible code.

like image 454
Giggi Avatar asked Oct 06 '22 21:10

Giggi


1 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 it's the simplest way, but it works.

Edit: you're right that this is slower than using slices; but you cannot create a slice object with arbitrary values. Maybe you should just do several assignments then:

%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
like image 194
Lev Levitsky Avatar answered Oct 13 '22 10:10

Lev Levitsky