Python: combining and rearranging arrays

Viewed 47

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

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

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.

Related