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