【问题标题】:Unravel Index numpy - own implementationUnravel Index numpy - 自己的实现
【发布时间】:2019-11-21 07:13:11
【问题描述】:

我尝试自己实现np.unravel_indexnp.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 找到一个类似的短(单行)函数。有人有想法吗?

【问题讨论】:

  • 从非单行实现开始,然后看看如何使它更简洁。但是一个班轮只是为了它不一定是好事......

标签: python numpy indexing


【解决方案1】:

这是一种可能的实现方式:

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]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-22
    • 2016-05-02
    • 2012-02-12
    • 1970-01-01
    • 2017-09-19
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多