Flatten numpy array but also keep index of value positions?

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

    You could also let pandas do the work for you since you'll be using it in a dataframe:

    x = np.array([[3, 1, 4],
                  [1, 5, 9],
                  [2, 6, 5]])
    df=pd.DataFrame(x)
    #unstack the y columns so that they become an index then reset the
    #index so that indexes become columns.
    df=df.unstack().reset_index()
    df
    
       level_0  level_1  0
    0        0        0  3
    1        0        1  1
    2        0        2  2
    3        1        0  1
    4        1        1  5
    5        1        2  6
    6        2        0  4
    7        2        1  9
    8        2        2  5
    
    #name the columns and switch the column order
    df.columns=['x','y','V']
    cols = df.columns.tolist()
    cols = cols[-1:] + cols[:-1]
    df = df[cols]
    df
    
       V  x  y
    0  3  0  0
    1  1  0  1
    2  2  0  2
    3  1  1  0
    4  5  1  1
    5  6  1  2
    6  4  2  0
    7  9  2  1
    8  5  2  2
    

提交回复
热议问题