美文网首页
Numpy-02:ndarray operation(meth

Numpy-02:ndarray operation(meth

作者: 罗泽坤 | 来源:发表于2020-03-18 14:36 被阅读0次

    根据官方文档主要内容如下:
    Array conversion(数据转换)
    Array shape manipulation(形状操作)
    Array Item selection and manipulation(数据选择与操作)
    Array Calculation(数据计算)
    Array Special methods(主要涉及算数运算)
    由于涉及的方法很多主要介绍联系一些实用的即可,其他由特殊需求可直接查看官方文档

    Array conversion

    | ndarray.item(args) | Copy an element of an array to a standard Python scalar and return it. |
    | ndarray.tolist() | Return the array as an a.ndim-levels deep nested list of Python scalars. |
    | ndarray.itemset(
    args) | Insert scalar into an array (scalar is cast to array’s dtype, if possible) |
    | ndarray.tostring([order]) | Construct Python bytes containing the raw data bytes in the array. |
    | ndarray.tobytes([order]) | Construct Python bytes containing the raw data bytes in the array. |
    | ndarray.tofile(fid[, sep, format]) | Write array to a file as text or binary (default). |
    | ndarray.dump(file) | Dump a pickle of the array to the specified file. |
    | ndarray.dumps() | Returns the pickle of the array as a string. |
    | ndarray.astype(dtype[, order, casting, …]) | Copy of the array, cast to a specified type. |
    | ndarray.byteswap([inplace]) | Swap the bytes of the array elements |
    | ndarray.copy([order]) | Return a copy of the array. |
    | ndarray.view([dtype, type]) | New view of array with the same data. |
    | ndarray.getfield(dtype[, offset]) | Returns a field of the given array as a certain type. |
    | ndarray.setflags([write, align, uic]) | Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY), respectively. |
    | ndarray.fill(value) | Fill the array with a scalar value. |

    Shape manipulation

    For reshape, resize, and transpose, the single tuple argument may be replaced with n integers which will be interpreted as an n-tuple.

    | ndarray.reshape(shape[, order]) | Returns an array containing the same data with a new shape. |
    | ndarray.resize(new_shape[, refcheck]) | Change shape and size of array in-place. |
    | ndarray.transpose(*axes) | Returns a view of the array with axes transposed. |
    | ndarray.swapaxes(axis1, axis2) | Return a view of the array with axis1 and axis2 interchanged. |
    | ndarray.flatten([order]) | Return a copy of the array collapsed into one dimension. |
    | ndarray.ravel([order]) | Return a flattened array. |
    | ndarray.squeeze([axis]) | Remove single-dimensional entries from the shape of a. |

    #先定义一个随机数数组和一个一维数组
    import numpy as np
    rmatrix = np.random.randint(10,size=(3,3))
    D1 = np.array([1])
    print(D1)
    print(rmatrix)
    
    [1]
    [[7 4 0]
     [4 5 3]
     [4 3 6]]
    
    # item函数的使用返回数组值
    print(D1.item())           #item方法没有设置参数这只对size=1的数组有效
    print(rmatrix.item(0))     #item方法中其实内部调用了flat方法将数组降成一维然后在取值
    print(rmatrix.item(4))
    print(rmatrix.item(8))
    print(rmatrix.item((0,0)))  #注意用下表组合的形式时不能超过数组维数
    print(rmatrix.item())   #注意此种方式是错误的
    
    1
    7
    5
    6
    7
    
    
    
    ---------------------------------------------------------------------------
    
    ValueError                                Traceback (most recent call last)
    
    <ipython-input-8-c84aee7a18f1> in <module>
          5 print(rmatrix.item(8))
          6 print(rmatrix.item((0,0)))
    ----> 7 print(rmatrix.item())   #注意此种方式是错误的
    
    
    ValueError: can only convert an array of size 1 to a Python scalar
    
    # itemset进行值设置
    rmatrix.itemset(0,0)
    rmatrix.itemset((1,1),0)
    rmatrix.itemset((2,2),0)
    print(rmatrix)
    
    [[0 4 0]
     [4 0 3]
     [4 3 0]]
    
    # tolist,tostring,tobytes进行数据结构转换
    print(rmatrix.tolist())
    print(rmatrix.tostring())
    print(rmatrix.tobytes())
    print(rmatrix.tofile('matrix.text',sep = '@',format = '%03d'))
    #第一个参数可以是:文件名 与 一个打开的文件描述符对象。
    #文件名的位置:如果不使用绝对位置,相对位置就是保存在ipynb文件作为相对位置。
    #输出结果:000@004@000@004@000@003@004@003@000
    
    [[0, 4, 0], [4, 0, 3], [4, 3, 0]]
    b'\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00'
    b'\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00'
    None
    
    # astype对数组进行数据处理后return一个新数组
    a = np.array([[1.1,2.2,3.3],[4.4,5.5,6.6],[7.7,8.8,9.9]],np.float)
    print(a)
    print(a.astype(np.int32))
    # copy方法使用
    print(a.copy())  # 直接copy一个数组
    
    [[1.1 2.2 3.3]
     [4.4 5.5 6.6]
     [7.7 8.8 9.9]]
    [[1 2 3]
     [4 5 6]
     [7 8 9]]
    [[1.1 2.2 3.3]
     [4.4 5.5 6.6]
     [7.7 8.8 9.9]]
    
    # 数据视图view
    print(a.view(dtype=np.int32))  #dtype设置数据类型
    print(a.view(type=np.ndarray)  #数组类型
    print(a.view(type=np.matrix))  #矩阵类型
    
    [[-1717986918  1072798105 -1717986918  1073846681  1717986918  1074423398]
     [-1717986918  1074895257           0  1075183616  1717986918  1075471974]
     [ -858993459  1075760332 -1717986918  1075943833  -858993459  1076088012]]
    [[1.1 2.2 3.3]
     [4.4 5.5 6.6]
     [7.7 8.8 9.9]]
    [[1.1 2.2 3.3]
     [4.4 5.5 6.6]
     [7.7 8.8 9.9]]
    
    c = a.view(type=np.ndarray)
    d = a.view(type=np.matrix)
    print(type(c))
    print(type(d))
    print(c.shape)
    print(d.shape)
    # 注意数组能是任意维数的但是矩阵只能是二维的
    print(c.reshape(1,3,3))
    print(d.reshape(1,3,3))
    
    <class 'numpy.ndarray'>
    <class 'numpy.matrix'>
    (3, 3)
    (3, 3)
    [[[1.1 2.2 3.3]
      [4.4 5.5 6.6]
      [7.7 8.8 9.9]]]
    [[1.1 2.2 3.3]
     [4.4 5.5 6.6]
     [7.7 8.8 9.9]]
    
    print(np.array([[[1]]]))#数组能是任意维不会报错
    print(np.mat([[[1]]]))#矩阵只能是2维会报错
    
    [[[1]]]
    
    
    
    ---------------------------------------------------------------------------
    
    ValueError                                Traceback (most recent call last)
    
    <ipython-input-56-8f3de4ef06e7> in <module>
          1 print(np.array([[[1]]]))#数组能是任意维不会报错
    ----> 2 print(np.mat([[[1]]]))#矩阵只能是2维会报错
    
    
    D:\Anaconda\lib\site-packages\numpy\matrixlib\defmatrix.py in asmatrix(data, dtype)
         69 
         70     """
    ---> 71     return matrix(data, dtype=dtype, copy=False)
         72 
         73 
    
    
    D:\Anaconda\lib\site-packages\numpy\matrixlib\defmatrix.py in __new__(subtype, data, dtype, copy)
        149         shape = arr.shape
        150         if (ndim > 2):
    --> 151             raise ValueError("matrix must be 2-dimensional")
        152         elif ndim == 0:
        153             shape = (1, 1)
    
    
    ValueError: matrix must be 2-dimensional
    
    #现在我们来看一下view与copy的差别在哪里
    print(a)
    e = a.view()
    c = a.copy()
    print(a)
    print(c)
    
    [[1.1 2.2 3.3]
     [4.4 5.5 6.6]
     [7.7 8.8 9.9]]
    [[1.1 2.2 3.3]
     [4.4 5.5 6.6]
     [7.7 8.8 9.9]]
    [[1.1 2.2 3.3]
     [4.4 5.5 6.6]
     [7.7 8.8 9.9]]
    
    c[0][0] = 0
    print(c)
    print(a)       #修改copy数组的值不会影响到原来的值
    
    [[0.  2.2 3.3]
     [4.4 5.5 6.6]
     [7.7 8.8 9.9]]
    [[1.1 2.2 3.3]
     [4.4 5.5 6.6]
     [7.7 8.8 9.9]]
    
    e[0][0] = 0    #因为视图的数据与原数组的数据空间是一样的
    print(e)        #修改视图数据会改变原数组数据
    print(a)        
    print(a.reshape(1,9))
    
    [[0.  2.2 3.3]
     [4.4 5.5 6.6]
     [7.7 8.8 9.9]]
    [[0.  2.2 3.3]
     [4.4 5.5 6.6]
     [7.7 8.8 9.9]]
    
    #原数组视图copy数组他们的结构存储地址都是不同的
    #原数组的数据和视图数据的引用是一致的
    #改变视图的shape不会改变原数组的shape
    print(id(a))
    print(id(c))
    print(id(e))
    
    2253826302000
    2253826304880
    2253826304160
    
    #填充数据fill
    a.fill(6)
    print(a)
    
    [[6. 6. 6.]
     [6. 6. 6.]
     [6. 6. 6.]]
    
    m = np.random.randint(10,size = (3,4))
    print(m)
    
    [[6 3 5 7]
     [3 3 0 6]
     [4 2 3 6]]
    
    print(m.reshape(4,3)) #有返回值不会改变m
    print(m)
    print(m.resize(2,6))  #resize没有返回值会改变m
    print(m)
    
    [[6 3 5]
     [7 3 3]
     [0 6 4]
     [2 3 6]]
    [[6 3 5 7 3 3]
     [0 6 4 2 3 6]]
    None
    [[6 3 5 7 3 3]
     [0 6 4 2 3 6]]
    

    transpose与swapaxes函数

    n = np.random.randint(10,size=(5,6))
    print(n)
    
    [[9 7 8 7 4 9]
     [0 4 8 8 7 3]
     [8 4 6 6 3 7]
     [3 2 7 2 5 1]
     [3 9 1 2 3 2]]
    
    print(n.transpose())
    print(n)
    
    [[9 0 8 3 3]
     [7 4 4 2 9]
     [8 8 6 7 1]
     [7 8 6 2 2]
     [4 7 3 5 3]
     [9 3 7 1 2]]
    [[9 7 8 7 4 9]
     [0 4 8 8 7 3]
     [8 4 6 6 3 7]
     [3 2 7 2 5 1]
     [3 9 1 2 3 2]]
    
    print(n.transpose(1,0))
    print(n.transpose(0,1))
    
    [[9 0 8 3 3]
     [7 4 4 2 9]
     [8 8 6 7 1]
     [7 8 6 2 2]
     [4 7 3 5 3]
     [9 3 7 1 2]]
    [[9 7 8 7 4 9]
     [0 4 8 8 7 3]
     [8 4 6 6 3 7]
     [3 2 7 2 5 1]
     [3 9 1 2 3 2]]
    
    |-transpose中参数说明:
        如果是二维数组,第一个参数代表行维度,第二个参数代表是列维度默认情况下
        第一个参数值是0,第二个参数值是1,把0和1交换就意味着交换两个维度把行变
        成列,列变成行
        如果是多维的那么原来数组参数的对应维度取值为0,1,2,3...依次增加,transpose中要想交换维度即进行坐标
        轴变换交换将维度取值交换写成参数即可拿下面的三维数组举例
    
    D3 = np.random.randint(10,size=(3,3,3))
    print(D3)
    
    [[[2 2 3]
      [2 3 9]
      [8 6 4]]
    
     [[4 3 2]
      [4 3 8]
      [7 1 0]]
    
     [[2 9 4]
      [5 3 2]
      [0 1 5]]]
    
    #下面两个变换等价因为transpose不加参数的时候
    #就是将默认参数进行了一次左移
    print(D3.transpose())
    print(D3.transpose(1,2,0))
    
    [[[2 4 2]
      [2 4 5]
      [8 7 0]]
    
     [[2 3 9]
      [3 3 3]
      [6 1 1]]
    
     [[3 2 4]
      [9 8 2]
      [4 0 5]]]
    [[[2 4 2]
      [2 3 9]
      [3 2 4]]
    
     [[2 4 5]
      [3 3 3]
      [9 8 2]]
    
     [[8 7 0]
      [6 1 1]
      [4 0 5]]]
    
    D = D3.transpose(1,2,0)
    print(D3[1][2][0])
    print(D[2][0][1])
    #下面用一段简单的for循环遍历D3看是否与transpose(1,2,0)D对应元素位置相等
    L = 0
    for i in range(3):
        for j in range(3):
            for k in range(3):
                if D3[i][j][k]==D[j][k][i]:
                    L = L + 1           #记录对应元素相等的数量结果应该为3x3x3=27
                else:
                    break
                pass
            pass
        pass
    print(L)                
    
    7
    7
    27
    
    |-由上面的代码示例可以很清楚的了解transpose中参数的含义:
        比如三维的transpose(2,1,0),因为原来数组的参数值是0,1,2
        现在变成了2,1,0这就相当于是说原来数组中坐标为[i][j][k]的元素
        在变换后的数组中坐标为[k][j][i]就这么个意思
        其实反映在空间直角坐标系中x,y,z轴就是三个axis,transpose也就相当于是
        进行坐标轴变换
    
    # ndarray.swapaxes(axis1,axis2)交换两维度参数顺序任意
    k = np.random.randint(10,size=(2,3,4))
    print(k)
    
    [[[0 8 1 9]
      [4 9 1 0]
      [9 3 2 4]]
    
     [[1 3 1 3]
      [9 4 3 3]
      [1 0 6 8]]]
    
    print(k.transpose(0,2,1))
    print(k.swapaxes(1,2))
    
    [[[0 4 9]
      [8 9 3]
      [1 1 2]
      [9 0 4]]
    
     [[1 9 1]
      [3 4 0]
      [1 3 6]
      [3 3 8]]]
    [[[0 4 9]
      [8 9 3]
      [1 1 2]
      [9 0 4]]
    
     [[1 9 1]
      [3 4 0]
      [1 3 6]
      [3 3 8]]]
    
    print(k.swapaxes(2,1))
    
    [[[0 4 9]
      [8 9 3]
      [1 1 2]
      [9 0 4]]
    
     [[1 9 1]
      [3 4 0]
      [1 3 6]
      [3 3 8]]]
    
    #一下三式是想等的
    print(k.swapaxes(0,1))
    print(k.swapaxes(1,0))
    print(k.transpose(1,0,2))
    
    [[[0 8 1 9]
      [1 3 1 3]]
    
     [[4 9 1 0]
      [9 4 3 3]]
    
     [[9 3 2 4]
      [1 0 6 8]]]
    [[[0 8 1 9]
      [1 3 1 3]]
    
     [[4 9 1 0]
      [9 4 3 3]]
    
     [[9 3 2 4]
      [1 0 6 8]]]
    [[[0 8 1 9]
      [1 3 1 3]]
    
     [[4 9 1 0]
      [9 4 3 3]]
    
     [[9 3 2 4]
      [1 0 6 8]]]
    

    flatten,ravel,squezze函数的使用

    P = np.random.randint(10,size=(3,4,1))
    print(P)
    
    [[[8]
      [3]
      [6]
      [3]]
    
     [[2]
      [5]
      [1]
      [4]]
    
     [[2]
      [7]
      [0]
      [4]]]
    
    #flatten与ravel的作用一样的都是转化成一维
    #注意flat函数是变成一维迭代器
    print(P.flatten())
    print(P.ravel())
    print(P)
    
    [8 3 6 3 2 5 1 4 2 7 0 4]
    [8 3 6 3 2 5 1 4 2 7 0 4]
    [[[8]
      [3]
      [6]
      [3]]
    
     [[2]
      [5]
      [1]
      [4]]
    
     [[2]
      [7]
      [0]
      [4]]]
    
    print(P.squeeze()) #删除长度为一的维度
    
    [[8 3 6 3]
     [2 5 1 4]
     [2 7 0 4]]
    
    print(P.shape)
    
    (3, 4, 1)
    
    #如果有多个维度为1则需要指明否则全部删除
    print(P.squeeze(axis=2))
    
    [[8 3 6 3]
     [2 5 1 4]
     [2 7 0 4]]
    
    j = np.random.randint(10,size=(3,1,1))
    print(j)
    print(j.squeeze(axis=2))
    print(j.squeeze())
    
    [[[7]]
    
     [[7]]
    
     [[7]]]
    [[7]
     [7]
     [7]]
    [7 7 7]
    
    
    

    相关文章

      网友评论

          本文标题:Numpy-02:ndarray operation(meth

          本文链接:https://www.haomeiwen.com/subject/cnnqyhtx.html