在列表索引为numpy的阵列中的多个片 [英] Multiple slice in list indexing for numpy array
问题描述
numpy的阵列承认指数列表,例如
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
这code返回一条错误消息:
This code returns an error message:
IndexError: too many indices
我的问题很简单:
你知道如果 numpy的或 SciPy的存在使用这种索引的一个有效的方法?
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?
不要忘了片的使用产生一个非常快的code;我的问题是要有更快地code。
Don't forget that the usage of slices produce a very fast code; and my problem is to have as faster as possible code.
推荐答案
什么在我脑海中:
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.
编辑:你说得对,这是比使用切片慢;但你不能创建任意值切片对象。也许你应该只是做几个任务,则:
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
这篇关于在列表索引为numpy的阵列中的多个片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!