Flatten numpy array but also keep index of value positions?

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

    The class np.ndindex is especially meant for this, and easily does the trick. Similar efficiency to the np.mesgrid method above, but it requires less code:

    indices = np.array(list(np.ndindex(x.shape)))
    

    For the dataframe, do:

    df = pd.DataFrame({'V': x.flatten(), 'x': indices[:, 0], 'y': indices[:, 1]})
    

    If you don't need the dataframe, just do list(np.ndindex(x.shape)).

    Note: don't get confused between x (the array at hand), and 'x' (the name of the second column).

    I know this question was posted a very long time ago, but just in case it's useful to anyone, as I didn't see np.ndindex being mentioned.

提交回复
热议问题