【问题标题】:Getting nearest index in Numpy在 Numpy 中获取最近的索引
【发布时间】:2014-12-21 14:06:11
【问题描述】:

将 numpy 导入为 np

我有一个给定的数组(a):

a = np.array([[99,2,3,4,99],
              [6,7,8,99,10]])

我有 3 个参考数组(b、c 和 d):

b = np.array([[99,12,13,14,99],
              [16,17,99,99,20]])

c = np.array([[21,22,23,24,99],
              [26,27,99,99,30]])

d = np.array([[31,32,33,34,35],
              [36,37,99,99,40]])

引用数组以这种形式一起给出:

references = np.array([b,c,d])

我必须使用最近的索引替换给定数组“a”中的值“99” 如果“非 99”值可用,则来自参考数组的值。

预期的答案是:

answer = np.array([[21,2,3,4,35],
              [6,7,8,99,10]])

最快的方法是什么?

【问题讨论】:

    标签: arrays numpy indexing


    【解决方案1】:

    你可以使用np.select:

    import numpy as np
    
    a = np.array([[99,2,3,4,99],
                  [6,7,8,99,10]])
    
    b = np.array([[99,12,13,14,99],
                  [16,17,99,99,20]])
    
    c = np.array([[21,22,23,24,99],
                  [26,27,99,99,30]])
    
    d = np.array([[31,32,33,34,35],
                  [36,37,99,99,40]])
    
    references = np.array([b,c,d])
    
    choices = np.concatenate([a[None, ...], references])
    conditions = (choices != 99)
    
    print(np.select(conditions, choices, default=99))
    

    产量

    [[21  2  3  4 35]
     [ 6  7  8 99 10]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-14
      相关资源
      最近更新 更多