我希望从numpy数组中获得索引列表(或数组)的结果,其形式为:(len(索引),(一个索引操作的形状))。
有没有办法直接使用索引列表,而不使用for循环,就像我在mininal示例中使用的那样,如下所示?
c = np.random.randint(0, 5, size=(4, 5))
indices = [[0, slice(0, 4)], [1, slice(0, 4)], [1, slice(0, 4)], [2, slice(0, 4)]]
# desired result using a for loop
res = []
for idx in indices:
res.append(c[idx])应该注意的是,索引列表并不代表我的问题,它只是一个例子,通常它是在运行时生成的。但是,每个索引操作都返回相同的形状
发布于 2015-09-04 16:29:38
看起来你基本上是从2D输入数组的开头开始切片,直到2 rows和4 columns,然后拆分每一行。您可以使用c[:2,:4]进行切片,然后使用np.vsplit拆分行,从而获得一个单行解决方案,如下所示-
res_out = np.vsplit(c[:2,:4],2)示例运行-
In [10]: c
Out[10]:
array([[0, 2, 5, 1, 0],
[1, 5, 5, 0, 3],
[0, 1, 0, 6, 6],
[2, 6, 2, 3, 3]])
In [11]: indices
Out[11]: [[0, slice(0, 4, None)], [1, slice(0, 4, None)]]
In [12]: # desired result using a for loop
...: res = []
...: for idx in indices:
...: res.append(c[idx])
...:
In [13]: res
Out[13]: [array([0, 2, 5, 1]), array([1, 5, 5, 0])]
In [14]: np.vsplit(c[:2,:4],2)
Out[14]: [array([[0, 2, 5, 1]]), array([[1, 5, 5, 0]])]请注意,np.vsplit的输出将是二维数组的列表,而不是问题中发布的代码中的一维数组列表。
https://stackoverflow.com/questions/32393217
复制相似问题