numpy的常用操作

1. expand_dims

numpy.expand_dims(a, axis)

 在给定的axis中插入一个新的axis以扩充array的shape。

  • axis:需要扩充轴axes的位置

2. squeeze

numpy.squeeze(a, axis=None)

 从array中remove轴的大小为1的。

  • axis:指定需要remove轴大小为1的轴
>>> x = np.array([[[0], [1], [2]]])
>>> x.shape
(1, 3, 1)
>>> np.squeeze(x).shape
(3,)
>>> np.squeeze(x, axis=0).shape
(3, 1)
>>> np.squeeze(x, axis=1).shape
Traceback (most recent call last):
...
ValueError: cannot select an axis to squeeze out which has size not equal to one

3. repeat

numpy.repeat(a, repeats, axis=None)

 重复array中的元素。

  • repeats:重复的次数
  • axis:沿其重复值的轴。

Axis的理解

可以将其理解为剥洋葱,如下图所示,axis=0表示第一层(对应黑色框),axis=1表示第二层(对应红色框),axis=2表示第三层(对应蓝色框)。

对于axis轴的操作,numpy会沿着第i个下标变化的方向进行操作。

>>> a
array([[1, 2],
       [3, 4]])
>>> np.repeat(a, 2, axis=0)
array([[1, 2],
       [1, 2],
       [3, 4],
       [3, 4]])
>>> np.repeat(a, 2, axis=1)
array([[1, 1, 2, 2],
       [3, 3, 4, 4]])

4. transpose

numpy.transpose(a, axes=None)

 反转或置换数组的轴; 返回修改后的数组。

image = cv2.imread("image-file.jpg")   # BGR | HWC order

image = image.transpose(2, 0, 1)        # CHW order

# rgb = bgr[...,::-1]
image = image[..., ::-1]                # BGR -> RGB

# cv2.cvtColor(	src, cv2.COLOR_BGR2GRAY ) ->	dst

5. ndarray的属性

  • 基础属性

ndarray.shape

Tuple of array dimensions.

ndarray.size

Number of elements in the array.

ndarray.dtypedataType
  • 内存分配

ndarray.itemsize

Length of one array element in bytes.

(数组中一个元素所占用的字节)

ndarray.nbytes

Total bytes consumed by the elements of the array.

(该数值总共占用的字节数)

6. 创建ndarray

ones(shape[, dtype, order, like])

Return a new array of given shape and type, filled with ones.(给定array的shape和type,值都为1)

ones_like(a[, dtype, order, subok, shape])

Return an array of ones with the same shape and type as a given array.(基于一个已有的array得到相应的shape和type)

zeros(shape[, dtype, order, like])

Return a new array of given shape and type, filled with zeros.(给定array的shape和type,值都为0)

zeros_like(a[, dtype, order, subok, shape])

Return an array of zeros with the same shape and type as a given array.(基于一个已有的array得到相应的shape和type)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值