如何在numpy中连接几个2D数组



我想要

np.concatenate((np.array([[5,5],[2,3]]),np.array([[6,4],[7,8]])))

以产生

[ [[5,5],[2,3]], [[6,4],[7,8]] ]

串联不起作用,但我不知道该怎么做!

您可以使用numpy.stack()numpy.append()(如果您有大型代码,我建议使用append(。只需注意它是numpy的append。不是python内置的append

>>> import numpy as np
>>> a = np.array([[5,5],[2,3]])
>>> b = np.array([[6,4],[7,8]])
>>> np.append([a], [b], axis = 0)
# answer: 
array([[[5, 5],
[2, 3]],
[[6, 4],
[7, 8]]])

现在,如果我们使用np.stack():

>>> d = np.stack((a,b))
>>> c == d
# answer:
array([[[ True,  True],
[ True,  True]],
[[ True,  True],
[ True,  True]]])

正如你所看到的,它们是一样的
您可以在此处看到numpy.append的用户指南,在此处可以看到numpy.vstack的用户指南。

对于任何想知道np.stack((a,b))能起作用的人来说:(

最新更新