我有一個包含值的 5D numpy 陣列,并希望獲得一個維度少的子陣列,其中的值是基于包含第一個陣列第四維索引的 3D 陣列選擇的。例如,我有以下陣列:
values = np.random.randn(3,4,5,10,2)
indices = np.random.randint(0,values.shape[3],size=values.shape[:3])
我找到了一個解決方案,但發現它相當復雜,并且更喜歡單線:
x = np.arange(values.shape[0])
y = np.arange(values.shape[1])
z = np.arange(values.shape[2])
result = values[x[:,None,None],y[None,:,None],z[None, None,:],indices,:]
有沒有更好的解決方案來獲得這個陣列?
uj5u.com熱心網友回復:
您可以嘗試以下操作:
indices = indices[..., None, None]
result = np.take_along_axis(values, indices, axis=3).squeeze(axis=3)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/389400.html
