官方文档:ravel_multi_index
numpy.ravel_multi_index(multi_index, dims, mode=‘raise’, order=‘C’)
multi_index - 类数组的元组。整数数组的元组,每个维度一个数组;
dims - 整数元组。multi_index的索引将应用到的数组的shape;
mode - 可选:“raise”、“wrap”、“clip”,指定如何处理越界索引。可以指定一个模式或一组模式,每个索引一个模式。其中,raise为默认,表示引发错误。
order - 可选:“C”和“F”,确定是否应将多索引视为按行优先(C)或列优先(F)的索引。
raveled_indices - ndarray类型。 官方解释为:An array of indices into the flattened version of an array of dimensions dims.
例1:
>>> import numpy as np >>> >>> arr = np.array([[3,6,6],[4,5,1]]) >>> np.ravel_multi_index(arr, (7,6)) array([22, 41, 37], dtype=int64) >>>代码分析: 该代码默认以“行”优先。在7x6的数组中,取其中(3,6)、(6,5)、(6,1)位置对应的索引数组中的索引值,如下图: 由上图可以得到以下规律: [3, 4] ——> 3 * 6 + 4 = 22 [6, 1] ——> 6 * 6 + 5 = 41 [6, 5] ——> 6 * 6 + 1 = 37
例2:
>>> import numpy as np >>> >>> arr = np.array([[3,6,6],[4,5,1]]) >>> np.ravel_multi_index(arr, (7,6), order='F') array([31, 41, 13], dtype=int64) >>>代码分析: 该代码以“列”优先,在7x6的数组中,取其中(3,6)、(6,5)、(6,1)位置对应的索引数组中的索引值,如下图: 由上图可以得到以下规律: [3, 4] ——> 3 + 4 * 7 = 31 [6, 1] ——> 6 + 5 * 7 = 41 [6, 5] ——> 6 + 1 * 7 = 13
例3:
>>> import numpy as np >>> >>> arr = np.array([[3,6,6],[4,5,1]]) >>> np.ravel_multi_index(arr, (4,6), mode='clip') array([22, 23, 19], dtype=int64) >>>例4:
>>> import numpy as np >>> >>> arr = np.array([[3,6,6],[4,5,1]]) >>> np.ravel_multi_index(arr, (4,4), mode=('clip','wrap')) array([12, 13, 13], dtype=int64)例3和例4都是以“行”优先,只是设置了不同的“mode”参数,大家可以自己运行以上代码,详细了解其功能。