numpy.repeat()
作用
可以用于重复数组中的元素
语法
numpy.repeat(a, repeats, axis=None)
参数解读
Parameters
- a : array_like
Input array.- repeats : int or array of ints
The number of repetitions for each element.repeats
is broadcasted
to fit the shape of the given axis.- axis : int, optional
The axis along which to repeat values. By default, use the
flattened input array, and return a flat output array.
- a: array_like
输入的想要进行repeat的数组 - repeats:int or array of ints
repeats
参数应该是int类型或者是一个int数组。是对每一个元素repeat的次数。repeats
将被广播去适应给定axis
的shape。 - axis: int, optional
repeat操作进行的维度,可选,int值。如果未指定,默认情况下,会将数组展平(flattened),然后返回一个扁平的重复后的数组。
Returns
- repeated_array : ndarray
Output array which has the same shape asa
, except along
the given axis.
- repeated_array : ndarray
返回的repeat后的数组,除了在指定的axis
维度以外,其余各维度的shape与原数组a
一致。
Example
>>> np.repeat(3, 4)
array([3, 3, 3, 3])
# 下面这个例子中,x被展平(flattened,返回的数组也是一个扁平数组)
>>> x = np.array([[1,2],[3,4]])
>>> np.repeat(x, 2)
array([1, 1, 2, 2, 3, 3, 4, 4])
# 下面这个例子指定了axis=1,axis=1的维度上的shape值为2,
# 而只给定了3一个数字,所以进行了广播,即进行的操作实际为(3,3)
>>> np.repeat(x, 3, axis=1)
array([[1, 1, 1, 2, 2, 2],
[3, 3, 3, 4, 4, 4]])
# 下面这个例子指定了axis=0,同时给定了repeats数组
# 其长度等于axis=0的shape值。对第一行重复1次,对第二行重复两次。
>>> np.repeat(x, [1, 2], axis=0)
array([[1, 2],
[3, 4],
[3, 4]])
# 如果给定的repeats数组长度与axis不一致,会报错,can not broadcast
>>> y = np.array([[1,2],[3,4],[5,6],[7,8]])
>>> np.repeat(y,(3,1),axis = 0)
ValueError: operands could not be broadcast together with shape (4,) (2,)
# 如果未指定axis,默认展平,但是repeats是数组,同样会报错。
>>> np.repeat(y,(3,1))
ValueError: operands could not be broadcast together with shape (8,) (2,)
类似的函数
如果repeat的功能和你想象中的不一致,那么你可能寻找的是这个函数:
numpy.tile(A,reps)
它的功能是:用A,按照reps指定的次数拼成一个新的数组。
numpy.tile解读