简体   繁体   中英

Numpy array insert every second element from second array

I have two arrays of the same shape and now want to combine them by making every odd element and 0 one of the first array and every even one of the second array in the same order. Eg:

a = ([0,1,3,5])
b = ([2,4,6])

c = ([0,1,2,3,4,5,6])

I tried something including modulo to identify uneven indices:

a = ([0,1,3,5])
b = ([2,4,6])

c = a

i = 0
j = 2
l = 0

for i in range(1,22):
    k = (i+j) % 2
    if k > 0:
        c = np.insert(c, i, b[l])
        l+=1
    else: 
        continue

I guess there is some easier/faster slicing option, but can't figure it out.

np.insert would work well:

>>> A = np.array([1, 3, 5, 7])
>>> B = np.array([2, 4, 6, 8])
>>> np.insert(B, np.arange(len(A)), A)
array([1, 2, 3, 4, 5, 6, 7, 8])

However, if you don't rely on sorted values, try this:

>>> A = np.array([5, 3, 1])
>>> B = np.array([1, 2, 3])
>>> C = [ ]
>>> for element in zip(A, B):
        C.extend(element)
>>> C
[5, 1, 3, 2, 1, 3]

read the documentation of the range

for i in range(0,10,2):
  print(i)

will print [0,2,4,6,8]

From what I understand, the first element in a is always first the rest are just intereleaved. If that is the case, then some clever use of stacking and reshaping is probably enough.

a = np.array([0,1,3,5])
b = np.array([2,4,6])
c = np.hstack([a[:1], np.vstack([a[1:], b]).T.reshape((-1, ))])

You could try something like this

import numpy as np

A = [0,1,3,5]
B = [2,4,6]
lst = np.zeros(len(A)+len(B))

lst[0]=A[0]
lst[1::2] = A[1:]
lst[2::2] = B

Even though I don't understand why you would make it so complicated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM