【问题标题】:How to give float indexes to numpy ndarray?如何为 numpy ndarray 提供浮点索引?
【发布时间】:2019-05-21 09:23:51
【问题描述】:

在时间序列数据中,我有一个在二维网格上演化的对象的 (x,y) 坐标。例如:

(41.797, 34.0),
(42.152, 34.56),
(42.383, 36.07),
(42.505, 37.97)

如何以 array[x,y]=object_id 的方式索引数组。随后,我需要再次通过这个时间索引的二维网格,并索引 array[x',y']=object_id_2。其中 x' 和 y' 就像上面的列表。

【问题讨论】:

  • 这些objects 是什么?他们已经创建了吗?你需要创建它们吗?你能修改这些objects吗?

标签: python numpy


【解决方案1】:

可以使用浮点索引来索引 numpy 数组,您只需要在值之间进行插值。这是使用双线性插值的代码(取自gist

def subsample_image(coords, img):
    """
    Given a list of floating point coordinates (Nx2) in the image,
    return the pixel value at each location using bilinear interpolation.
    """
    if len(img.shape) == 2:
        img = np.expand_dims(img, 2)
    xs, ys = coords[:, 0], coords[:, 1]
    pxs = np.floor(xs).astype(int)
    pys = np.floor(ys).astype(int)
    dxs = xs-pxs
    dys = ys-pys
    wxs, wys = 1.0-dxs, 1.0-dys
    
    weights =  np.multiply(img[pys, pxs, :].T      , wxs*wys).T
    weights += np.multiply(img[pys, pxs+1, :].T    , dxs*wys).T
    weights += np.multiply(img[pys+1, pxs, :].T    , wxs*dys).T
    weights += np.multiply(img[pys+1, pxs+1, :].T  , dxs*dys).T
    return weights

【讨论】:

    【解决方案2】:

    这里有一些问题。

    首先,您不能按浮点数进行索引,因为它没有任何意义。 其次,如果可以的话,解释/计算浮点数的方式存在问题(有时您的结果类似于 3.99999999 而不是 4 的原因)。

    我的建议是使用四舍五入到一定小数位数的字典来索引您的值。这样您将确保您的数据始终匹配!

    由于您无法通过不可变键映射内容,因此您需要一个元组。

    这是如何工作的示例:

    mydict = {}
    
    a = (41.797, 34.0)
    object_a = 'A'
    b = (42.152, 34.56)
    object_b 'B'
    
    mydict[round(a[0], 3), round(a[1], 3)] = object_a
    mydict[round(b[0], 3), round(b[1], 3)] = object_b
    
    print ( my_dict[round(a[0], 3), round(a[1], 3)] )
    print ( my_dict[round(b[0], 3), round(b[1], 3)] )
    
    >> 'A'
    >> 'B'
    

    如果要更新对象,只需使用圆角元组

    mydict[round(a[0], 3), round(a[1], 3)] = 'CHICKEN'
    
    
    print ( my_dict[round(a[0], 3), round(a[1], 3)] )
    print ( my_dict[round(b[0], 3), round(b[1], 3)] )
    
    >> 'CHICKEN'
    >> 'B'
    

    如果代码变得太乱,只需添加一个函数来舍入元组:

    def round_tuple(tupl, decimals=3):
        return round(tupl[0], decimals), round(tupl[1], decimals)
    
    This way you just do this:
    target = round_tuple(tup)
    mydict[target] = 'CHICKEN'
    

    【讨论】:

      猜你喜欢
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2018-02-15
      相关资源
      最近更新 更多