【笔记】Python:numpy中的ravel_multi_index函数

ravel_multi_index函数:

官方文档: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”参数,大家可以自己运行以上代码,详细了解其功能。

  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值