giosans
giosans

Reputation: 1178

Transform x,y numpy matrixes into a list of (x,y) points

I have

x=np.array([[1,2,3],[3,4,5],[5,7,8]])
y=np.array([[5,2,5],[1,1,1],[2,2,2]])

I'd like to get

xy=[(1,5),(2,2),(3,5),(3,1),(4,1),(5,1),(5,2),(7,2),(8,2)]

What's the best (quick and clean) way to do so? Also, once I have xy, how do I relate the indexes of xy to the original numpy matrixes x,y ?

Upvotes: 0

Views: 1664

Answers (3)

Harsha Biyani
Harsha Biyani

Reputation: 7268

You can try:

>>> x = [[1,2,3],[3,4,5],[5,7,8]]
>>> y = [[5,2,5],[1,1,1],[2,2,2]]
>>> x1 = [val for x_data in x for val in x_data]
>>> y1 = [val for y_data in y for val in y_data]
>>> final = [(a,b) for a, b in zip(x1, y1)]
>>> print final
[(1, 5), (2, 2), (3, 5), (3, 1), (4, 1), (5, 1), (5, 2), (7, 2), (8, 2)]

Upvotes: 1

Colonel Beauvel
Colonel Beauvel

Reputation: 31171

You can use this approach to get xy:

zip(x.flatten(),y.flatten())

#[(1, 5), (2, 2), (3, 5), (3, 1), (4, 1), (5, 1), (5, 2), (7, 2), (8, 2)]

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107287

Transpose or use nop.dstack():

>>> np.dstack((x.ravel(), y.ravel()))[0]
array([[1, 5],
       [2, 2],
       [3, 5],
       [3, 1],
       [4, 1],
       [5, 1],
       [5, 2],
       [7, 2],
       [8, 2]])
>>> 
>>> 
>>> np.array((x.ravel(), y.ravel())).T
array([[1, 5],
       [2, 2],
       [3, 5],
       [3, 1],
       [4, 1],
       [5, 1],
       [5, 2],
       [7, 2],
       [8, 2]])

Upvotes: 0

Related Questions