Python中如何将二维数组的行列索引映射到一维数组索引?
二维数组索引映射到一维数组的方法
对于方形二维数组,已知行索引 i 和列索引 j,要映射到一维数组的索引 idx,可以用以下公式:
idx = i * 列数 + j
其中“列数”是二维数组每行的元素个数(因为是方形数组,列数等于行数)。
示例验证
以你给出的例子为例:
- 二维数组
mat是2行2列的数组,列数为2import numpy as np mat = np.array([[6, 7], [8, 9]]) arr = np.array([1, 2, 3, 4]) - 映射计算:
mat[0,0]:0*2 + 0 = 0→ 对应arr[0]mat[0,1]:0*2 + 1 = 1→ 对应arr[1]mat[1,0]:1*2 + 0 = 2→ 对应arr[2]mat[1,1]:1*2 + 1 = 3→ 对应arr[3]
如果需要批量转换或在numpy中直接操作,也可以用np.ravel_multi_index函数,传入行索引、列索引和数组形状即可得到一维索引:
# 比如获取mat[1,0]的一维索引 idx = np.ravel_multi_index((1, 0), mat.shape) # idx的值为2,对应arr[2]
内容的提问来源于stack exchange,提问作者statwoman
相关产品推荐
相关产品推荐

