Home > OS >  How to combine two arrays for a specific index without concatenation?
How to combine two arrays for a specific index without concatenation?

Time:06-10

I have two arrays that I want to merge to a new one but I need to insert the indices in specific places

array1 = np.arange(95,320,4)
array2 = np.arange(0,360,2)

For example.. array1[0] = 95, but I want this value to be in a new array between array2[47] which equals 94 and array2[48] that equals 96, and so on with the rest of the values inside array1.

Is this possible?

CodePudding user response:

I think that you're looking for numpy.insert

array1 = np.arange(95,320,4)
array2 = np.arange(0,360,2)

for i, value in enumerate(array1):
  index = i 48 i*2
  array2 = np.insert(array2, index, array1[i])

CodePudding user response:

It is not clear what you want exactly, but it might be the following:

So you have two arrays (arr1 and arr2):

import numpy as np

arr1 = np.arange(95, 320, 4)
arr2 = np.arange(0, 360, 2)

And you have two lists of indexes (idxs1 and idxs2) mapping between those arrays' elements and their index in the merged array:

n1, n2 = len(arr1), len(arr2)
n = n1   n2

idxs = np.arange(n)

rng = np.random.default_rng()
rng.shuffle(idxs)

idxs1 = idxs[:n1]
idxs2 = idxs[n1:]

Then you can construct the merged array pretty easily as so:

merged = np.empty(n)
merged[idxs1] = arr1
merged[idxs2] = arr2

Let's check the properties I assumed you want to achieved:

for i in range(n1):
    assert merged[idxs1[i]] == arr1[i]

for i in range(n2):
    assert merged[idxs2[i]] == arr2[i]
  • Related