Python:连接(或克隆)一个 numpy 数组 N 次
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22634265/
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
Python: Concatenate (or clone) a numpy array N times
提问by stelios
I want to create an MxN numpy array by cloning a Mx1 ndarray N times. Is there an efficient pythonic way to do that instead of looping?
我想通过克隆 Mx1 ndarray N 次来创建一个 MxN numpy 数组。有没有一种有效的pythonic方法来做到这一点而不是循环?
Btw the following way doesn't work for me (X is my Mx1 array) :
顺便说一句,以下方式对我不起作用(X 是我的 Mx1 数组):
numpy.concatenate((X, numpy.tile(X,N)))
since it created a [M*N,1] array instead of [M,N]
因为它创建了一个 [M*N,1] 数组而不是 [M,N]
采纳答案by Cory Kramer
You are close, you want to use np.tile, but like this:
你很接近,你想使用np.tile,但像这样:
a = np.array([0,1,2])
np.tile(a,(3,1))
Result:
结果:
array([[0, 1, 2],
[0, 1, 2],
[0, 1, 2]])
If you call np.tile(a,3)you will get concatenatebehavior like you were seeing
如果你打电话,np.tile(a,3)你会得到concatenate像你看到的那样的行为
array([0, 1, 2, 0, 1, 2, 0, 1, 2])
http://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html
http://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html
回答by Samy Arous
Have you tried this:
你有没有试过这个:
n = 5
X = numpy.array([1,2,3,4])
Y = numpy.array([X for _ in xrange(n)])
print Y
Y[0][1] = 10
print Y
prints:
印刷:
[[1 2 3 4]
[1 2 3 4]
[1 2 3 4]
[1 2 3 4]
[1 2 3 4]]
[[ 1 10 3 4]
[ 1 2 3 4]
[ 1 2 3 4]
[ 1 2 3 4]
[ 1 2 3 4]]

