[英]slice index using numpy array
Consider the following code:考虑以下代码:
import numpy as np
np.random.seed(0)
x = np.random.randint(0,9,(10,10,3))
x[np.array([0,1]):np.array([5,6])]
I get the following error:我收到以下错误:
TypeError: only integer scalar arrays can be converted to a scalar index
I guess I would need to unpack the arrays that index x
but can't figure out a way to do it since *
doesn't work.我想我需要解压索引为x
的 arrays,但由于*
不起作用,所以无法找到解决方法。
The goal is to have x[0:5]
and x[1:6]
目标是让x[0:5]
和x[1:6]
Due to requests I'm posting here a solution for the problem I was looking for:由于要求,我在这里发布了我正在寻找的问题的解决方案:
import numpy as np
np.random.seed(0)
x = np.random.randint(0,9,(10,10,3))
arr1,arr2 = np.array([0,1]),np.array([5,6])
slices = []
for i,j in zip(arr1,arr2):
slices.append(x[i:j])
print(slices)
This way I can have both slices as requested ie x[0:5]
and x[1:6]
.这样我就可以按要求拥有两个切片,即x[0:5]
和x[1:6]
。 If anyone has a method on how to approach this problem without a for loop it would be very helpful.如果有人知道如何在没有 for 循环的情况下解决这个问题,那将非常有帮助。 Thanks.谢谢。
here is the another one,这是另一个,
import numpy as np
np.random.seed(0)
x = np.random.randint(0,9,(10,10,3))
[x[i:j] for i,j in zip(np.array([0,1]),np.array([5,6]))]
if I have understood the question right, you should not use ":" in x[np.array([0,1]):np.array([0,1])]如果我理解正确的问题,你不应该在x[np.array([0,1]):np.array([0,1])]中使用“:”
use "," instead x[np.array([0,1]),np.array([0,1])]使用 "," 代替x[np.array([0,1]),np.array([0,1])]
You could generate an index array similar to this answer .您可以生成类似于此答案的索引数组。
import numpy as np
x = np.random.randint(0,9,(10,10,3))
idcs = np.array([
np.arange(0,5),
np.arange(1,6),
])
print(x.shape)
# (10, 10, 3)
print(x[idcs].shape)
# (2, 5, 10, 3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.