python - 如何找到向量化矩阵 numpy 的索引

标签 python numpy matrix

我在 numpy (n x n x n) 中有一个 ndmatrix,我对其进行矢量化以便以特定方式对我的数据进行一些采样,得到 (1 x n^3)。

我想采用单独的向量化索引并将它们转换回形式为 (n x n x n) 的 n 维索引。我不确定矢量化矩阵实际上有多颠簸。

谁能给个建议?

最佳答案

Numpy 有一个函数 unravel_index,它的作用非常大:给定一组“平面”索引,它将返回每个维度中索引数组的元组:

>>> indices = np.arange(25, dtype=int)
>>> np.unravel_index(indices, (5, 5))
(array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4,
        4, 4], dtype=int64),
 array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2,
        3, 4], dtype=int64))

然后您可以压缩它们以获得您的原始索引。

但是请注意,矩阵可以表示为“行序列”(C 约定,'C')或“列序列”(Fortran 约定,'F'), 或更高维度的相应约定。 numpy 中典型的矩阵展平将保留该顺序,因此 [[1, 2], [3, 4]] 可以展平为 [1, 2, 3, 4](如果它有 'C' 顺序)或 [1, 3, 2, 4](如果它有 'F' 顺序)。 unravel_index 如果您想更改默认值(即“C”),则采用可选的 order 参数,因此您可以:

>>> # Typically, transposition will change the order for
>>> # efficiency reasons: no need to change the data !
>>> n = np.random.random((2, 2, 2)).transpose() 
>>> n.flags.f_contiguous
True
>>> n.flags.c_contiguous
False
>>> x, y, z = np.unravel_index([1,2,3,7], (2, 2, 2), order='F')

关于python - 如何找到向量化矩阵 numpy 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36615683/

相关文章:

matlab - 如何遍历 matlab 中矩阵的列并将它们分别添加到 matlab 中求和矩阵的特定列?

python - 需要的建议 : learning material for Django

python - 3D 线击中 3D 点?

python - 如何规范 pandas 数据框中的以下日期?

python - 使用 numpy.save 保存 Numpy 二维数组列表(数组一起呈锯齿状)

python - 有没有办法将 np.where() 与列列表一起使用?

c++添加操作菜单

python - findChild 使用自定义小部件返回 None

Python Find max in dataframe 列以循环查找所有值

matlab - 从相应的最大矩阵中选取值