创建索引矩阵/索引列表的更简单方法? [英] Simpler way to create a matrix/list of indices?
问题描述
我想知道创建二维数组的最简单方法是什么,该数组对于每一行都有另一个多维数组的索引.
I wonder what could be the easiest way to create a bi-dimensional array, that has for each row the indices to another multi-dimensional array.
例如,假设我有一个4x4立方体,则索引矩阵"如下:
For example, let's say I have a cube 4x4, the "indices matrix" would be the following:
np.concatenate([
np.expand_dims(curr.ravel(),axis=0).T
for curr
in np.meshgrid(
np.arange(4),
np.arange(4),
np.arange(4)
)
],axis=1)
具有以下结果:
array([[0, 0, 0],
[0, 0, 1],
[0, 0, 2],
[0, 0, 3],
[1, 0, 0],
[1, 0, 1],
...
[2, 3, 2],
[2, 3, 3],
[3, 3, 0],
[3, 3, 1],
[3, 3, 2],
[3, 3, 3]])
除了第二列似乎应该代替第一列之外,还有没有更多的"numpythonic"方式以更紧凑的方式创建相同或相似的矩阵?
Besides the fact that it seems that the second column should be in place of the first, is there a more "numpythonic" way to create the same or similar matrix in a more compact way?
如果存在一个仅接受任意多维数组并返回其索引表的函数,那就太好了.
It would be nice if existed a function that just takes an arbitrary multi-dimensional array and returns it's index table.
推荐答案
您可以使用 np.indices
:
You could use np.indices
:
>>> a = np.random.random((4,4,4))
>>> np.indices(a.shape).reshape((a.ndim, -1)).T
array([[0, 0, 0],
[0, 0, 1],
[0, 0, 2],
[0, 0, 3],
[0, 1, 0],
[0, 1, 1],
[...]
[3, 3, 2],
[3, 3, 3]])
还有其他实用程序,例如 np.ndindex
,具体取决于您的用例. (FWIW,我认为以您想要的形式获取坐标不会像您认为的那样有用,但是YMMV.)
There are also other utilities like np.ndindex
, depending on your use case. (FWIW I don't think getting the coordinates in the form you're looking for is going to be as helpful as you might think it is, but YMMV.)
这篇关于创建索引矩阵/索引列表的更简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!