Flatten numpy array but also keep index of value positions?

前端 未结 9 1290
北荒
北荒 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条回答
  •  旧时难觅i
    2021-02-04 14:25

    I am resurrecting this because I think I know a different answer that is way easier to understand. Here is how I do it:

    xn = np.zeros((np.size(x), np.ndim(x)+1), dtype=np.float32)
    row = 0
    for ind, data in np.ndenumerate(x):
        xn[row, 0] = data
        xn[row, 1:] = np.asarray(ind)
        row += 1
    

    In xn we have

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

提交回复
热议问题