Python NumPy 追加与连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35932101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:09:57 来源:igfitidea点击:
NumPy append vs concatenate
提问by Jana
What is the difference between NumPy append
and concatenate
?
NumPyappend
和 有concatenate
什么区别?
My observation is that concatenate
is a bit faster and append
flattens the array if axis is not specified.
我的观察是,如果未指定轴,它concatenate
会更快一些并且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])
回答by hpaulj
np.append
uses np.concatenate
:
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)