NumPy追加vs串联 [英] NumPy append vs concatenate

查看:52
本文介绍了NumPy追加vs串联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

NumPy appendconcatenate有什么区别?

What is the difference between NumPy append and concatenate?

我的观察是,如果未指定轴,则concatenate会快一点,而append会使数组变平.

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

推荐答案

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)

这篇关于NumPy追加vs串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆