【发布时间】:2018-02-18 11:27:45
【问题描述】:
此问题基于this 较早的问题:
给定一个数组:
In [122]: arr = np.array([[1, 3, 7], [4, 9, 8]]); arr Out[122]: array([[1, 3, 7], [4, 9, 8]])并给出它的索引:
In [127]: np.indices(arr.shape) Out[127]: array([[[0, 0, 0], [1, 1, 1]], [[0, 1, 2], [0, 1, 2]]])我怎样才能将它们整齐地堆叠在一起以形成 一个新的二维数组?这就是我想要的:
array([[0, 0, 1], [0, 1, 3], [0, 2, 7], [1, 0, 4], [1, 1, 9], [1, 2, 8]])
This solution by Divakar 是我目前用于二维数组的方法:
def indices_merged_arr(arr):
m,n = arr.shape
I,J = np.ogrid[:m,:n]
out = np.empty((m,n,3), dtype=arr.dtype)
out[...,0] = I
out[...,1] = J
out[...,2] = arr
out.shape = (-1,3)
return out
现在,如果我想传递一个 3D 数组,我需要修改这个函数:
def indices_merged_arr(arr):
m,n,k = arr.shape # here
I,J,K = np.ogrid[:m,:n,:k] # here
out = np.empty((m,n,k,4), dtype=arr.dtype) # here
out[...,0] = I
out[...,1] = J
out[...,2] = K # here
out[...,3] = arr
out.shape = (-1,4) # here
return out
但是这个函数现在只适用于 3D 数组 - 我不能将 2D 数组传递给它。
有没有某种方法可以将其概括为适用于任何维度?这是我的尝试:
def indices_merged_arr_general(arr):
tup = arr.shape
idx = np.ogrid[????] # not sure what to do here....
out = np.empty(tup + (len(tup) + 1, ), dtype=arr.dtype)
for i, j in enumerate(idx):
out[...,i] = j
out[...,len(tup) - 1] = arr
out.shape = (-1, len(tup)
return out
我遇到了这条线的问题:
idx = np.ogrid[????]
我怎样才能让它工作?
【问题讨论】:
-
看起来像
np.ndenumerate -
@hpaulj 这看起来是另一个不错的选择。我现在正在想办法解开这些索引。
-
@coldspeed 太糟糕了,ndenumerate 的例子被删除了,用 int 表示 i,j (x,y) 和 k (z) 表示 float 构造一个索引数组是最简单的。
-
@NaN 我删除了我的答案,因为 hpaulj 发布了他自己的答案。
标签: python arrays numpy indexing