1

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.

1
  • print(list(map(list, zip(A,B)))) ? Commented Jul 30, 2018 at 17:48

2 Answers 2

1

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]])
Sign up to request clarification or add additional context in comments.

4 Comments

How do you select 1 or 2 from the stacked array? Select individual element from the sublists?
To select from the first column, start indexing using arr[:, 0], and for the second column, use arr[:, 1]
I tried that, but it will give me an entire column. I only need the individual element such as 1,2 or 4
Just read up on numpy indexing, if you wanted 1, you would use the first row, first column, so arr[0, 0]
1

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)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.