[python] 두 개의 numpy 배열 짜기

다음 배열이 주어진다고 가정하십시오.

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

이렇게 세 번째 배열을 얻을 수 있도록 효율적으로 짜맞추는 방법

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

가정 할 수 있습니다 length(a)==length(b).



답변

나는 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


답변

성능 측면에서 솔루션의 성능을 확인하는 것이 가치가 있다고 생각했습니다. 그리고 이것이 그 결과입니다.

여기에 이미지 설명 입력

이것은 가장 많이 찬성되고 수락 된 답변 (Pauls 답변) 이 가장 빠른 옵션 임을 분명히 보여줍니다 .

코드는 다른 답변과 다른 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

다른 대안보다 약간 더 빠를 수 있습니다.

여기에 이미지 설명 입력


답변

다음은 한 줄짜리입니다.

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


답변

다음은 이전 답변보다 간단한 답변입니다.

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


답변

이것은 두 배열을 인터리브 / 인터레이스 할 것이며 꽤 읽기 쉽다고 생각합니다.

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])


답변

아마도 이것은 @JoshAdel의 솔루션보다 더 읽기 쉽습니다.

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


답변

@xioxox의 답변 개선 :

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