NumPy append与concatenate的区别

41

NumPy中appendconcatenate有什么区别?

我观察到concatenate稍微比append快一点,而append会将数组压平,如果未指定轴。

In [52]: print a
[[1 2]
 [3 4]
 [5 6]
 [5 6]
 [1 2]
 [3 4]
 [5 6]
 [5 6]
 [1 2]
 [3 4]
 [5 6]
 [5 6]
 [5 6]]

In [53]: print b
[[1 2]
 [3 4]
 [5 6]
 [5 6]
 [1 2]
 [3 4]
 [5 6]
 [5 6]
 [5 6]]

In [54]: timeit -n 10000 -r 5 np.concatenate((a, b))
10000 loops, best of 5: 2.05 µs per loop

In [55]: timeit -n 10000 -r 5 np.append(a, b, axis = 0)
10000 loops, best of 5: 2.41 µs per loop

In [58]: np.concatenate((a, b))
Out[58]: 
array([[1, 2],
       [3, 4],
       [5, 6],
       [5, 6],
       [1, 2],
       [3, 4],
       [5, 6],
       [5, 6],
       [1, 2],
       [3, 4],
       [5, 6],
       [5, 6],
       [5, 6],
       [1, 2],
       [3, 4],
       [5, 6],
       [5, 6],
       [1, 2],
       [3, 4],
       [5, 6],
       [5, 6],
       [5, 6]])

In [59]: np.append(a, b, axis = 0)
Out[59]: 
array([[1, 2],
       [3, 4],
       [5, 6],
       [5, 6],
       [1, 2],
       [3, 4],
       [5, 6],
       [5, 6],
       [1, 2],
       [3, 4],
       [5, 6],
       [5, 6],
       [5, 6],
       [1, 2],
       [3, 4],
       [5, 6],
       [5, 6],
       [1, 2],
       [3, 4],
       [5, 6],
       [5, 6],
       [5, 6]])

In [60]: np.append(a, b)
Out[60]: 
array([1, 2, 3, 4, 5, 6, 5, 6, 1, 2, 3, 4, 5, 6, 5, 6, 1, 2, 3, 4, 5, 6, 5,
       6, 5, 6, 1, 2, 3, 4, 5, 6, 5, 6, 1, 2, 3, 4, 5, 6, 5, 6, 5, 6])

2
np.append жШѓеЯЇдЇО np.concatenate еЃЪдєЙзЪДгАВиѓЈеПВиІБ https://github.com/numpy/numpy/blob/v1.10.0/numpy/lib/function_base.py#L4098-L4150гАВ - Dan D.
1个回答

75

np.append 使用 np.concatenate

def append(arr, values, axis=None):
    arr = asanyarray(arr)
    if axis is None:
        if arr.ndim != 1:
            arr = arr.ravel()
        values = ravel(values)
        axis = arr.ndim-1
    return concatenate((arr, values), axis=axis)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接