2

I have two arrays:

array1=[[1,2],
        [3,4],
        [8,9]]

array2=[[11,12],
        [13,14],
        19,20]]

How can I combine the arrays to an array which looks like:

array=[([[1,11],
       [3,13],
       [8,19]]),
array([[[2,12],
       [4,14],
       [9,20]])]
      


Thank you in advance!

2 Answers 2

2

You can use np.concatenate, First output array can be created by concatenating first column of array1 and array2 along the axis =1, and similarly for second output array take second column from array1 and array2.

Use:

new_arr1 = np.concatenate((array1[:, 0:1], array2[:, 0:1]), axis = 1)
new_arr2 = np.concatenate((array1[:, 1:2], array2[:, 1:2]), axis = 1)

Output:

>>> new_arr1
array([[ 1, 11],
       [ 3, 13],
       [ 8, 19]])
>>> new_arr2
array([[ 2, 12],
       [ 4, 14],
       [ 9, 20]])

If you don't want to keep the original array we can do inplace changes which will only take extra memory for one column.

temp = array1[:, 1].copy()
array1[:, 1] = array2[:, 0]
array2[:, 0] = temp

Output:

>>> array1
array([[ 1, 11],
       [ 3, 13],
       [ 8, 19]])
>>> array2
array([[ 2, 12],
       [ 4, 14],
       [ 9, 20]])
Sign up to request clarification or add additional context in comments.

Comments

2

Use this:

import numpy as np
array_new1 = np.array([[a[0],b[0]] for a,b in zip(array1,array2)])
array_new2 = np.array([[a[1],b[1]] for a,b in zip(array1,array2)])

zip function will take many iterables (lists) and iterate each elements of all iterables (lists) parallely.

So, here I just iterated over 0 indexed element of both the arrays parallelly to get new array 1. It is done using list comprehension which is just another form of using for loop. For new array 2, I iterated over 1 indexed elements of both arrays parallelly and combined them using list comprehension.

3 Comments

Good answer, but it would be great if you explained a little regarding list comprehensions and zip.
@AlexMetsai Thank you for the comment, I tried my best to explain the answer :)
Thanks for the update, I have already upvoted your answer. :-)

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.