Python:连接(或克隆)一个numpy数组N次

时间:2021-12-09 02:25:29

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]

3 个解决方案

#1


36  

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 concatenate behavior like you were seeing

如果你调用np.tile(a,3),你会得到像你所看到的连接行为

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

#2


7  

You could use vstack:

你可以使用vstack:

numpy.vstack([X]*N)

e.g.

例如

    >>> import numpy as np
    >>> X = np.array([1,2,3,4])
    >>> N = 7
    >>> np.vstack([X]*N)
    array([[1, 2, 3, 4],
           [1, 2, 3, 4],
           [1, 2, 3, 4],
           [1, 2, 3, 4],
           [1, 2, 3, 4],
           [1, 2, 3, 4],
           [1, 2, 3, 4],
           [1, 2, 3, 4],
           [1, 2, 3, 4]])

#3


1  

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

#1


36  

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 concatenate behavior like you were seeing

如果你调用np.tile(a,3),你会得到像你所看到的连接行为

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

#2


7  

You could use vstack:

你可以使用vstack:

numpy.vstack([X]*N)

e.g.

例如

    >>> import numpy as np
    >>> X = np.array([1,2,3,4])
    >>> N = 7
    >>> np.vstack([X]*N)
    array([[1, 2, 3, 4],
           [1, 2, 3, 4],
           [1, 2, 3, 4],
           [1, 2, 3, 4],
           [1, 2, 3, 4],
           [1, 2, 3, 4],
           [1, 2, 3, 4],
           [1, 2, 3, 4],
           [1, 2, 3, 4]])

#3


1  

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