美文网首页
[numpy]numpy切片与索引

[numpy]numpy切片与索引

作者: Franckisses | 来源:发表于2019-03-07 16:46 被阅读0次

    简单的总结一下numpy中的切片和索引。

    先说索引。
    1.一维数组的索引。

    c = np.random.randint(10,size=8)
    >>array([7, 5, 5, 4, 2, 1, 2, 2])
    c[1]
    >>5
    c[-2]
    2
    c[0]
    >>7
    c[0] = 3.14159  #赋值给不同类型的元素。会导致
    array([3, 5, 5, 4, 2, 1, 2, 2])  
    

    2.二维数组的索引,要使用逗号将中间分隔开。前边是索引行。后边是索引列。

    d = np.random.randint(14, size=(3, 4))
    >>array([[ 8, 11, 10, 11],
             [ 4, 13, 13, 14],
             [ 0,  7, 11,  1]])
    d[0,0]  
    >>8
    d[1,2]
    >>13
    d2[2, -1]
    >>14
    d2[0, 0] = 12
    d
    >>array([[12, 11, 10, 11],
       [ 4, 13, 13, 13],
       [ 0,  7, 11,  1]])
    

    3.一维数组的切片。

    e = np.arange(10)
    >>array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    e[:5]
    >>array([0,1,2,3,4])
    e[5:]
    >>array([5,6,7,8,9])
    e[5:7]
    >>array([5,6])
    e[::2]
    >>array([0,2,4,6,8])
    e[1::2]
    >>array([1,3,5,7,9])
    e[::-1]
    >>array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
    e[5::-2]
    >>array([5,3,1])
    

    4.多维数组的切片。

    f = np.random.randint(10, size=(3, 4))
    f    
    >>array([[2, 9, 5, 1],
            [9, 8, 3, 9],
            [6, 3, 4, 3]])
    f[:2, :3]
    >>array([[12,  5,  2],
            [ 7,  6,  8]])
    f[:3, ::2] 
    >>array([[12,  2],
             [ 7,  8],
             [ 1,  7]])
    f[::-1, ::-1]
    >>array([[ 7,  7,  6,  1],
             [ 8,  8,  6,  7],
             [ 4,  2,  5, 12]])
    

    5.数组的链接。

    x = np.array([1, 2, 3])
    y = np.array([3, 2, 1])
    np.concatenate([x, y])
    >>array([1, 2, 3, 3, 2, 1])
    #也可以链接不止两个。
    z = [99, 99, 99]
    np.concatenate([x, y, z])
    >>array([ 1  2  3  3  2  1 99 99 99])
    grid = np.array([[1, 2, 3],
                     [4, 5, 6]])
    np.concatenate([grid,grid])
    >>array([[1, 2, 3],
         [4, 5, 6],
         [1, 2, 3],
         [4, 5, 6]])
    np.concatenate([grid,grid],axis=1)
    >>array([[1, 2, 3, 1, 2, 3],
           [4, 5, 6, 4, 5, 6]])
    

    6.数组的拆分。

    x = [1, 2, 3, 99, 99, 3, 2, 1]
    x1, x2, x3 = np.split(x, [3, 5])
    print(x1, x2, x3)
    >>[1 2 3] [99 99] [3 2 1]
    
    >>grid = np.arange(16).reshape((4, 4))
    grid
    >>array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
    
    upper, lower = np.vsplit(grid, [2])
    print(upper)
    print(lower)
    >>[[0 1 2 3]
      [4 5 6 7]]
      [[ 8  9 10 11]
      [12 13 14 15]]
    
    left, right = np.hsplit(grid, [2])
    print(left)
    print(right)
    >>[[ 0  1]
    [ 4  5]
    [ 8  9]
    [12 13]]
    [[ 2  3]
    [ 6  7]
    [10 11]
    [14 15]]
    

    相关文章

      网友评论

          本文标题:[numpy]numpy切片与索引

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