Create a 2D array from another array and its indices with NumPy

后端 未结 2 2031
悲&欢浪女
悲&欢浪女 2020-12-07 03:26

Given an array:

arr = np.array([[1, 3, 7], [4, 9, 8]]); arr

array([[1, 3, 7],
       [4, 9, 8]])

And given its indices:

np         


        
2条回答
  •  执笔经年
    2020-12-07 03:53

    A more generic answer for nd arrays, that handles other dtypes correctly:

    def indices_merged_arr(arr):
        out = np.empty(arr.shape, dtype=[
            ('index', np.intp, arr.ndim),
            ('value', arr.dtype)
        ])
        out['value'] = arr
        for i, l in enumerate(arr.shape):
            shape = (1,)*i + (-1,) + (1,)*(arr.ndim-1-i)
            out['index'][..., i] = np.arange(l).reshape(shape)
        return out.ravel()
    

    This returns a structured array with an index column and a value column, which can be of different types.

提交回复
热议问题