本文介绍了重复一个numpy数组的每个元素5次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import numpy as np
data = np.arange(-50,50,10)
print data
[-50 -40 -30 -20 -10 0 10 20 30 40]
我要重复数据的每个元素5次,并按如下所示制作新数组:
I want to repeat each element of data 5 times and make new array as follows:
ans = [-50 -50 -50 -50 -50 -40 -40 ... 40]我该怎么办?
将整个数组重复5次怎么样?
What about repeating the whole array 5 times?
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 .......]推荐答案
In [1]: data = np.arange(-50,50,10)
要重复每个元素5次,请使用 np.repeat :
To repeat each element 5 times use 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 :
To repeat the array 5 times use 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广播代替用重复的元素创建一个更大的数组.
Note, however, that sometimes you can take advantage of NumPy broadcasting instead of creating a larger array with repeated elements.
例如,如果
z = np.array([1, 2]) v = np.array([[3], [4], [5]])然后添加这些数组以生成
then to add these arrays to produce
[[4 5] [5 6] [6 7]]您不需要使用图块:
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将为您广播数组:
Instead, NumPy will broadcast the arrays for you:
In [15]: z + v Out[15]: array([[4, 5], [5, 6], [6, 7]])更多推荐
重复一个numpy数组的每个元素5次
发布评论