简体   繁体   English

Numpy 数组插入第二个数组中的每个第二个元素

[英]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.我有两个相同形状的 arrays,现在想通过以相同的顺序将第一个数组中的每个奇数元素和 0 和第二个数组中的每个偶数元素组合起来。 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: np.insert 会很好用:

>>> 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]将打印 [0,2,4,6,8]

From what I understand, the first element in a is always first the rest are just intereleaved.据我了解,a 中的第一个元素始终是第一个 rest 只是交织在一起。 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虽然我不明白你为什么要把它搞得这么复杂

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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