Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get x,y,value 1D arrays from 2D numpy array (linear indexing)

Tags:

python

numpy

Say I have a 2D array like the one below:

array([3, 6, 7
       1,-1, 3])

I would like to get in 3 separate arrays the x, y and value of the array . In other words:

x      = [0, 1, 0,  1, 0, 1]
y      = [0, 0, 1,  1, 2, 2]
values = [3, 1, 6, -1, 7, 3]

How can I do this?

For reference, this is what MATLAB calls linear indexing.

like image 671
Amelio Vazquez-Reina Avatar asked Dec 11 '22 10:12

Amelio Vazquez-Reina


2 Answers

How about something like:

x, y = np.indices(array.shape)
x = x.ravel(order='F')
y = y.ravel(order='F')
values = array.ravel(order='F')
like image 138
Bi Rico Avatar answered Feb 08 '23 22:02

Bi Rico


def xyval(A):
    x, y = np.indices(A.shape)
    return x.ravel(), y.ravel(), A.ravel()
like image 28
ali_m Avatar answered Feb 08 '23 22:02

ali_m