请考虑使用complete -F $(./a.out --generate-autocomplete-config) ./a.out
D1,形状为numpy.ndarray
。
我想构建一个形状为(10,N,M)
的新ndarray O1。这样:
(N*M,3)
,0≤i≤N
,仅考虑10个维度上的最小元素。让我们考虑一个2而不是10的小例子,目前的方法部分实现了我的目标:
0≤j≤M
通过这种方式,我获得了元素相对于2维的最小索引,但我失去了有关D1中初始索引的信息。
在这种情况下,预期输出应为:
>>> d1 = np.random.randint(20, size=2*3*3).reshape(2,3,3)
array([[[ 2, 6, 18],
[18, 18, 10],
[ 2, 3, 1]],
[[11, 3, 14],
[12, 14, 18],
[ 6, 8, 19]]])
>>> d2 = np.amin(d1, axis=0)
array([[ 2, 3, 14],
[12, 14, 10],
[ 2, 3, 1]])
>>> o1 = np.dstack(np.unravel_index(np.argsort(d2.ravel()), d2.shape))
array([[[2, 2],
[0, 0],
[2, 0],
[0, 1],
[2, 1],
[1, 2],
[1, 0],
[0, 2],
[1, 1]]])
答案 0 :(得分:2)
A structured array is a handy way to work with the indices and minimum values at the same time:
M, N = d1.shape[1:]
mi, ni = np.ogrid[:M, :N]
data = np.empty((M, N), [('coords', np.intp, 3), ('min', d1.dtype)])
data['coords'][..., 0] = mi
data['coords'][..., 1] = ni
data['coords'][..., 2] = np.argmin(d1, axis=0)
data['min'] = np.min(d1, axis=0)
data = data.ravel() # collapse (M, N) to (M*N,)
data_sorted = data[np.argsort(data['min'])]
o1 = data_sorted['coords']
But you can also get there easily from your code:
d2 = np.min(d1, axis=0)
arg_d2 = np.argmin(d1, axis=0)
order = np.argsort(d2.ravel())
mi, ni = np.unravel_index(order, d2.shape)
o1 = np.stack((mi, ni, arg_d2.ravel()[order]), axis=-1) # dstack but faster