简体   繁体   中英

Python: Numpy combine arrays into 2x1 lists

I'm hoping to combine two arrays

 A: ([1,2,5,8])
 B: ([4,6,7,9])

to

 C: ([[1,4],
      [2,6],
      [5,7],
      [8,9]])

I have tried insert, append and concatenate, they only lump all elements together without giving the dimension in C.

I'm new to Python, any help will be appreciated.

Use numpy.column_stack :

Stack 1-D arrays as columns into a 2-D array

np.column_stack((A, B))

array([[1, 4],
       [2, 6],
       [5, 7],
       [8, 9]])

According to your initial approach, you only need to use zip , which returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.

import numpy

A = numpy.array([1,2,5,8])
B = numpy.array([4,6,7,9])

print(list(zip(A, B)))

It will print:

[(1, 4), (2, 6), (5, 7), (8, 9)]

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