numpy.repeat作用,语法,参数解读以及实例

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 as a, 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解读

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值