Flatten numpy array but also keep index of value positions?

前端 未结 9 1267
北荒
北荒 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:30

    Another way:

    arr = np.array([[3, 1, 4],
                    [1, 5, 9],
                    [2, 6, 5]])
    
    # build out rows array
    x = np.arange(arr.shape[0]).reshape(arr.shape[0],1).repeat(arr.shape[1],axis=1)
    # build out columns array
    y = np.arange(arr.shape[1]).reshape(1,arr.shape[0]).repeat(arr.shape[0],axis=0)
    
    # combine into table
    table = np.vstack((arr.reshape(arr.size),x.reshape(arr.size),y.reshape(arr.size))).T
    print(table)
    

提交回复
热议问题