Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

python - Merge two arrays vertically to array of tuples using numpy

I have two numpy arrays:

x = np.array([-1, 0, 1, 2])
y = np.array([-2, -1, 0, 1])

Is there a way to merge these arrays together like tupples:

array = [(-1, -2), (0, -1), (1, 0), (2, 1)]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
In [469]: x = np.array([-1, 0, 1, 2])
In [470]: y = np.array([-2, -1, 0, 1])

join them into 2d array:

In [471]: np.array((x,y))
Out[471]: 
array([[-1,  0,  1,  2],
       [-2, -1,  0,  1]])

transpose that array:

In [472]: np.array((x,y)).T
Out[472]: 
array([[-1, -2],
       [ 0, -1],
       [ 1,  0],
       [ 2,  1]])

or use the standard Python zip - this treats the arrays as lists

In [474]: zip(x,y)   # list(zip in py3
Out[474]: [(-1, -2), (0, -1), (1, 0), (2, 1)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...