python - Unravel Index numpy - 自己的实现
问题描述
我尝试自己np.unravel_index
实施np.ravel_multi_index
。因为np.ravel_multi_index
我可以编写这个简短的函数:
def coord2index(coord, shape):
return np.concatenate((np.asarray(shape[1:])[::-1].cumprod()[::-1],[1])).dot(coord)
但我很难为np.unravel_index
. 有人有想法吗?
解决方案
这是一种可能的实现:
import numpy as np
def index2coord(index, shape):
return ((np.expand_dims(index, 1) // np.r_[1, shape[:0:-1]].cumprod()[::-1]) % shape).T
shape = (2, 3, 4)
coord = [[0, 1], [2, 0], [1, 3]]
print(index2coord(coord2index(coord, shape), shape))
# [[0 1]
# [2 0]
# [1 3]]
推荐阅读
- javascript - 使用fabric.JS将文本定位在一行的中点?
- typescript - 联合和扩展省略后属性不存在
- java - 尝试使用 freetts 生成 2 个 tts 文件时出现异常
- kubernetes - K8s/Openshift - 复制控制器是否关心 pod/容器的退出状态?
- c# - 尝试将项目添加到数据库时出现更新条目错误
- java - 我如何知道/收到通知我的活动 (android) 已结束?
- ssh - 如何在 Laradock 上使用 SSH?
- python - K_means聚类中的这些代码行是什么意思?
- python - Stellargraph:- 导入 stellargraph 时出现问题,即无法导入名称“softmax”
- javascript - 使用 Reduce 进行 MongoDB 重复数据删除和排序