2011-07-21 101 views
9

我试图使用argmin(或相关的argmax等函数)中的二维数组索引来对大型三维数组进行索引。这是我的数据。例如:NumPy:在3D片段中使用argmin中的二维索引数组

import numpy as np 
shape3d = (16, 500, 335) 
shapelen = reduce(lambda x, y: x*y, shape3d) 

# 3D array of [random] source integers 
intcube = np.random.uniform(2, 50, shapelen).astype('i').reshape(shape3d) 

# 2D array of indices of minimum value along first axis 
minax0 = intcube.argmin(axis=0) 

# Another 3D array where I'd like to use the indices from minax0 
othercube = np.zeros(shape3d) 

# A 2D array of [random] values I'd like to assign in othercube 
some2d = np.empty(shape3d[1:]) 

此时,两个三维阵列具有相同的形状,而minax0阵列具有的形状(500,335)。现在我想将2D数组some2d的值分配给3D数组othercube,使用minax0作为第一维的索引位置。这就是我想要的,但不工作:

othercube[minax0] = some2d # or 
othercube[minax0,:] = some2d 

引发错误:

ValueError: dimensions too large in fancy indexing

注:我目前使用的是什么,但不是很NumPythonic:

for r in range(shape3d[1]): 
    for c in range(shape3d[2]): 
     othercube[minax0[r, c], r, c] = some2d[r, c] 

我一直在挖掘网络寻找类似的例子,可以索引othercube,但我没有找到任何优雅。这是否需要advanced index?有小费吗?

+0

谢谢你有过这个问题!我的一天更适合它所引发的答案。 – Richard

回答

9

花式索引可能有点不直观。幸运的是,tutorial有一些很好的例子。

基本上,您需要定义j和k,其中每个minidx适用。 numpy不会从形状中推断出它。

在你的榜样:

i = minax0 
k,j = np.meshgrid(np.arange(335), np.arange(500)) 
othercube[i,j,k] = some2d 
+0

这将如何工作在3D索引数组从4D阵列? – Elvin