Home > Software design >  Insert an array into another array in numpy?
Insert an array into another array in numpy?

Time:06-12

How do I do this? (in a computationally efficient way)

arr1 = np.array([0, 4, 8, 12, 16])
arr2 = np.array([1, 5, 9, 13, 17])
arr3 = np.array([2, 6, 10, 14, 18])
arr4 = np.array([3, 7, 11, 15, 19])

what_i_want = [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]

CodePudding user response:

You can directly pass a list of arrays to np.ravel to flatten in Fortran order:

np.ravel([arr1, arr2, arr3, arr4], 'F')

Slower alternative with stack and ravel:

np.stack([arr1, arr2, arr3, arr4]).ravel('F')

output:

array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19])

CodePudding user response:

using transpose of np.vstack and flattening:

np.vstack((arr1, arr2, arr3, arr4)).T.ravel()
# np.array((arr1, arr2, arr3, arr4)).T.ravel()   # alternative way
"""
np.vstack

[[ 0  4  8 12 16]
 [ 1  5  9 13 17]
 [ 2  6 10 14 18]
 [ 3  7 11 15 19]]

np.vstack().T

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]
 [16 17 18 19]]

np.vstack().T.ravel()

[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]
"""

CodePudding user response:

Try with the following:

np.array([arr1, arr2, arr3, arr4]).T.reshape(1, -1)[0]

Output:

array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])

CodePudding user response:

I think this is the easiest way to reach your goal.

import numpy as np
arr1 = np.array([0, 4, 8, 12, 16])
arr2 = np.array([1, 5, 9, 13, 17])
arr3 = np.array([2, 6, 10, 14, 18])
arr4 = np.array([3, 7, 11, 15, 19])
newArray = np.array((arr1, arr2, arr3, arr4)).T.ravel()
print(newArray)

what_you_want:

Output :

[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]

CodePudding user response:

    #importing dependencies
    import numpy as np
    arr1 = np.array([0, 4, 8, 12, 16])
    arr2 = np.array([1, 5, 9, 13, 17])
    arr3 = np.array([2, 6, 10, 14, 18])
    arr4 = np.array([3, 7, 11, 15, 19])
    #creating an array to store results
    X = []
    #writing a loop to add each element(i) of the arr1,2,3,4 in the result. but                            
    all the arrays must be of the same lenght as are in your case.
    for i in range (0 , len(arr1)):
      X.append(arr1[i])
      X.append(arr2[i])
      X.append(arr3[i])
      X.append(arr4[i])
    print("X = " , X)  

CodePudding user response:

You can use np.concatenate like this:

what_you_want = np.concatenate((arr1, arr2, arr3, arr4))

Source: https://numpy.org/doc/stable/user/absolute_beginners.html#adding-removing-and-sorting-elements

You can also look this: https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html?highlight=concatenate#numpy.concatenate

  • Related