2011-07-21 41 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