Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

python - NumPy append vs concatenate

What is the difference between NumPy append and concatenate?

My observation is that concatenate is a bit faster and append flattens the array if axis is not specified.

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])
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

np.append uses 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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...