简体   繁体   中英

Python Numpy array conversion

I've got 2 numpy arrays x1 and x2. Using python 3.4.3

x1 = np.array([2,4,4])
x2 = np.array([3,5,3])

I would like to a numpy array like this:

[[2,3],[4,5],[4,3]]

How would i go about this?

You can use numpy.column_stack :

In [40]: x1 = np.array([2,4,4])

In [41]: x2 = np.array([3,5,3])

In [42]: np.column_stack((x1, x2))
Out[42]: 
array([[2, 3],
       [4, 5],
       [4, 3]])

Yep. It sounds like zip function:

import numpy as np 

x1 = np.array([2,4,4])
x2 = np.array([3,5,3])

print zip(x1, x2) # or [list(i) for i in zip(x1, x2)]

You can zip the 2 arrays like this:

x3 = list(zip(x1,x2))

Output:

[(2, 3), (4, 5), (4, 3)]

This above code creates a list of tuples . If you want a list of lists , you can use list comprehension :

x3 = [list(i) for i in list(zip(x1,x2))]

Output:

[[2, 3], [4, 5], [4, 3]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM