Flatten numpy array but also keep index of value positions?

前端 未结 9 1263
北荒
北荒 2021-02-04 13:58

I have several 2D numpy arrays (matrix) and for each one I would like to convert it to vector containing the values of the array and a vector containing each row/column index.

9条回答
  •  悲&欢浪女
    2021-02-04 14:11

    Like @miguel-capllonch I would suggest using np.ndindex which allows you to create the desired output like this:

    np.array([(v, *i) for (i, v) in zip(np.ndindex(x.shape), x.ravel())])
    

    which results in an array that looks like this:

    array([[ 3.  0.  0.]
           [ 1.  0.  1.]
           [ 4.  0.  2.]
           [ 1.  1.  0.]
           [ 5.  1.  1.]
           [ 9.  1.  2.]
           [ 2.  2.  0.]
           [ 6.  2.  1.]
           [ 5.  2.  2.]])
    

    Alternatively, using only numpy commands

    np.hstack((list(np.ndindex(x.shape)), x.reshape((-1, 1))))
    

提交回复
热议问题