重复一个numpy数组中的每个元素5次

41
import numpy as np

data = np.arange(-50,50,10)
print data

[-50 -40 -30 -20 -10   0  10  20  30  40]

我想将数据中的每个元素重复5次,并生成以下新数组:

ans = [-50 -50 -50 -50 -50 -40 -40 ... 40]

我该怎么做呢?

把整个数组重复五次怎么样?

ans =  [-50 -40 -30 -20 -10   0  10  20  30  40 -50 -40 -30 -20 -10   0  10  20  30  40 -50 -40 -30 -20 -10   0  10  20  30  40 -50 -40 -30 -20 -10   0  10  20  30  40 -50 -40 -30 -20 -10   0  10  20  30  40 .......]
2个回答

66
In [1]: data = np.arange(-50,50,10)

要重复每个元素5次,请使用np.repeat

In [3]: np.repeat(data, 5)
Out[3]: 
array([-50, -50, -50, -50, -50, -40, -40, -40, -40, -40, -30, -30, -30,
       -30, -30, -20, -20, -20, -20, -20, -10, -10, -10, -10, -10,   0,
         0,   0,   0,   0,  10,  10,  10,  10,  10,  20,  20,  20,  20,
        20,  30,  30,  30,  30,  30,  40,  40,  40,  40,  40])

要将数组重复5次,请使用np.tile

In [2]: np.tile(data, 5)
Out[2]: 
array([-50, -40, -30, -20, -10,   0,  10,  20,  30,  40, -50, -40, -30,
       -20, -10,   0,  10,  20,  30,  40, -50, -40, -30, -20, -10,   0,
        10,  20,  30,  40, -50, -40, -30, -20, -10,   0,  10,  20,  30,
        40, -50, -40, -30, -20, -10,   0,  10,  20,  30,  40])

请注意,有时您可以利用NumPy广播而不是创建具有重复元素的更大数组。
例如,如果
z = np.array([1, 2])
v = np.array([[3], [4], [5]])

然后将这些数组相加

 [[4 5]
  [5 6]
  [6 7]]

你不需要使用tile:

In [12]: np.tile(z, (3,1))
Out[12]: 
array([[1, 2],
       [1, 2],
       [1, 2]])

In [13]: np.tile(v, (1,2))
Out[13]: 
array([[3, 3],
       [4, 4],
       [5, 5]])

In [14]: np.tile(z, (3,1)) + np.tile(v, (1,2))
Out[14]: 
array([[4, 5],
       [5, 6],
       [6, 7]])

相反,NumPy会为您广播数组:
In [15]: z + v
Out[15]: 
array([[4, 5],
       [5, 6],
       [6, 7]])

7

只需要使用 np.repeat 函数:

In [5]: data.repeat(5)

Out[5]: 
array([-50, -50, -50, -50, -50, -40, -40, -40, -40, -40, -30, -30, -30,
       -30, -30, -20, -20, -20, -20, -20, -10, -10, -10, -10, -10,   0,
         0,   0,   0,   0,  10,  10,  10,  10,  10,  20,  20,  20,  20,
        20,  30,  30,  30,  30,  30,  40,  40,  40,  40,  40])

整个数组重复5次怎么样? - puti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接