Flatten numpy array but also keep index of value positions?

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

    I don't know if it's most efficient, but numpy.meshgrid is designed for this:

    x = np.array([[3, 1, 4],
                  [1, 5, 9],
                  [2, 6, 5]])
    XX,YY = np.meshgrid(np.arange(x.shape[1]),np.arange(x.shape[0]))
    table = np.vstack((x.ravel(),XX.ravel(),YY.ravel())).T
    print(table)
    

    This produces:

    [[3 0 0]
     [1 1 0]
     [4 2 0]
     [1 0 1]
     [5 1 1]
     [9 2 1]
     [2 0 2]
     [6 1 2]
     [5 2 2]]
    

    Then I think df = pandas.DataFrame(table) will give you your desired data frame.

提交回复
热议问题