交织两个numpy阵列

时间:2011-03-18 01:20:51

标签: python arrays numpy

假设给出以下数组:

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

如何有效地交织它们以便得到第三个这样的数组

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

可以假设length(a)==length(b)

11 个答案:

答案 0 :(得分:93)

我喜欢Josh的回答。我只是想添加一个更平凡,通常,稍微冗长的解决方案。我不知道哪个更有效率。我希望他们会有类似的表现。

import numpy as np
a = np.array([1,3,5])
b = np.array([2,4,6])

c = np.empty((a.size + b.size,), dtype=a.dtype)
c[0::2] = a
c[1::2] = b

答案 1 :(得分:33)

这是一个单行:

c = numpy.vstack((a,b)).reshape((-1,),order='F')

答案 2 :(得分:26)

我认为检查解决方案在性能方面的表现可能是值得的。这就是结果:

enter image description here

这清楚地表明most upvoted and accepted answer (Pauls answer)也是最快的选择。

代码来自其他答案,来自another Q&A

# Setup
import numpy as np

def Paul(a, b):
    c = np.empty((a.size + b.size,), dtype=a.dtype)
    c[0::2] = a
    c[1::2] = b
    return c

def JoshAdel(a, b):
    return np.vstack((a,b)).reshape((-1,),order='F')

def xioxox(a, b):
    return np.ravel(np.column_stack((a,b)))

def Benjamin(a, b):
    return np.vstack((a,b)).ravel([-1])

def andersonvom(a, b):
    return np.hstack( zip(a,b) )

def bhanukiran(a, b):
    return np.dstack((a,b)).flatten()

def Tai(a, b):
    return np.insert(b, obj=range(a.shape[0]), values=a)

def Will(a, b):
    return np.ravel((a,b), order='F')

# Timing setup
timings = {Paul: [], JoshAdel: [], xioxox: [], Benjamin: [], andersonvom: [], bhanukiran: [], Tai: [], Will: []}
sizes = [2**i for i in range(1, 20, 2)]

# Timing
for size in sizes:
    func_input1 = np.random.random(size=size)
    func_input2 = np.random.random(size=size)
    for func in timings:
        res = %timeit -o func(func_input1, func_input2)
        timings[func].append(res)

%matplotlib notebook

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(1)
ax = plt.subplot(111)

for func in timings:
    ax.plot(sizes, 
            [time.best for time in timings[func]], 
            label=func.__name__)  # you could also use "func.__name__" here instead
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xlabel('size')
ax.set_ylabel('time [seconds]')
ax.grid(which='both')
ax.legend()
plt.tight_layout()

如果您有可用的numba,您也可以使用它来创建一个函数:

import numba as nb

@nb.njit
def numba_interweave(arr1, arr2):
    res = np.empty(arr1.size + arr2.size, dtype=arr1.dtype)
    for idx, (item1, item2) in enumerate(zip(arr1, arr2)):
        res[idx*2] = item1
        res[idx*2+1] = item2
    return res

它可能比其他替代方案稍快:

enter image description here

答案 3 :(得分:18)

这是一个比以前的一些更简单的答案

import numpy as np
a = np.array([1,3,5])
b = np.array([2,4,6])
inter = np.ravel(np.column_stack((a,b)))

inter包含后:

array([1, 2, 3, 4, 5, 6])

这个答案似乎也略快一些:

In [4]: %timeit np.ravel(np.column_stack((a,b)))
100000 loops, best of 3: 6.31 µs per loop

In [8]: %timeit np.ravel(np.dstack((a,b)))
100000 loops, best of 3: 7.14 µs per loop

In [11]: %timeit np.vstack((a,b)).ravel([-1])
100000 loops, best of 3: 7.08 µs per loop

答案 4 :(得分:5)

也许这比@JoshAdel的解决方案更具可读性:

c = numpy.vstack((a,b)).ravel([-1])

答案 5 :(得分:5)

这将交错/交错两个数组,我相信它是可读的:

a = np.array([1,3,5])      #=> array([1, 3, 5])
b = np.array([2,4,6])      #=> array([2, 4, 6])
c = np.hstack( zip(a,b) )  #=> array([1, 2, 3, 4, 5, 6])

答案 6 :(得分:2)

改善@ xioxox的答案:

import numpy as np
a = np.array([1,3,5])
b = np.array([2,4,6])
inter = np.ravel((a,b), order='F')

答案 7 :(得分:1)

vstack肯定是一个选项,但更简单的解决方案可能是hstack

>>> a = array([1,3,5])
>>> b = array([2,4,6])
>>> hstack((a,b)) #remember it is a tuple of arrays that this function swallows in.
>>> array([1, 3, 5, 2, 4, 6])
>>> sort(hstack((a,b)))
>>> array([1, 2, 3, 4, 5, 6])

更重要的是,这适用于ab

的任意形状

您也可以尝试dstack

>>> a = array([1,3,5])
>>> b = array([2,4,6])
>>> dstack((a,b)).flatten()
>>> array([1, 2, 3, 4, 5, 6])

你现在有选择了!

答案 8 :(得分:1)

另一种形式:np.vstack((a,b)).T.ravel()
还有一个:np.stack((a,b),1).ravel()

答案 9 :(得分:0)

也可以尝试np.insert。 (从Interleave numpy arrays迁移的解决方案)

import numpy as np
a = np.array([1,3,5])
b = np.array([2,4,6])
np.insert(b, obj=range(a.shape[0]), values=a)

有关详细信息,请参阅documentationtutorial

答案 10 :(得分:0)

我需要执行此操作,但要沿任意轴使用多维数组。这是实现此目的的快速通用功能。它具有与np.concatenate相同的呼叫签名,除了所有输入数组必须具有完全相同的形状。

import numpy as np

def interleave(arrays, axis=0, out=None):
    shape = list(np.asanyarray(arrays[0]).shape)
    if axis < 0:
        axis += len(shape)
    assert 0 <= axis < len(shape), "'axis' is out of bounds"
    if out is not None:
        out = out.reshape(shape[:axis+1] + [len(arrays)] + shape[axis+1:])
    shape[axis] = -1
    return np.stack(arrays, axis=axis+1, out=out).reshape(shape)
相关问题