numpy 笔记

  • reshape 和 resize 的区别
    The reshape function returns its argument with a modified shape, whereas the ndarray.resize method modifies the array itself:
>>> a
array([[ 2.,  8.,  0.,  6.],
       [ 4.,  5.,  1.,  1.],
       [ 8.,  9.,  3.,  6.]])
>>> a.resize((2,6))
>>> a
array([[ 2.,  8.,  0.,  6.,  4.,  5.],
       [ 1.,  1.,  8.,  9.,  3.,  6.]])

  • no copy at all
>>> a = np.arange(12)
>>> b = a            # no new object is created
>>> b is a           # a and b are two names for the same ndarray object
True
  • deep copy
    The copy method makes a complete copy of the array and its data.
>>> d = a.copy()                          # a new array object with new data is created
>>> d is a
False
>>> d.base is a                           # d doesn't share anything with a
False

有时,如果不再需要原始数组,应该在切片之后调用copy。例如,假设a是一个巨大的中间结果,最终的结果b只包含了a的一小部分,那么在用切片构造b时,需要进行深度复制:

>>> a = np.arange(int(1e8))
>>> b = a[:100].copy()
>>> del a  # the memory of ``a`` can be released.
  • Indexing with Boolean Arrays
    布尔索引最常用的方法是使用与原始数组形状相同的布尔数组:
>>> a = np.arange(12).reshape(3,4)
>>> b = a > 4
>>> b                                          # b is a boolean with a's shape
array([[False, False, False, False],
       [False,  True,  True,  True],
       [ True,  True,  True,  True]])
>>> a[b]                                       # 1d array with the selected elements
array([ 5,  6,  7,  8,  9, 10, 11])

这个属性在赋值时非常有用:

>>> a[b] = 0               # All elements of 'a' higher than 4 become 0
>>> a
array([[0, 1, 2, 3],
       [4, 0, 0, 0],
       [0, 0, 0, 0]])
  • 我们可以对两个不同大小的矩阵执行运算, 前提是某一个矩阵维度为 1.此时, Numpy使用广播规则执行算术运算.
  • 图像

    图像是尺寸(高度 × 宽度) 的像素矩阵.

    如果图像是黑白(即灰度)的, 则每个像素都可以用单个数字表示(通常在0(黑色)和255(白色)之间).下面是一个图像文件的片段:

    在这里插入图片描述
如果图像是彩色的,则每个像素有三个数字表示---红色, 绿色和蓝色.

在这种情况下,我们需要一个三维数组. 因此彩色图像由尺寸为 (高 × 宽 × 3)的 ndarray 表示:
原文地址:https://www.cnblogs.com/larkiisready/p/11681635.html