📜  在 NumPy 中拆分数组

📅  最后修改于: 2022-05-13 01:54:23.441000             🧑  作者: Mango

在 NumPy 中拆分数组

阵列拆分可以是垂直的、水平的或深度方向的。我们可以分别使用函数hsplit()vsplit()dsplit() 。我们可以通过指示拆分应该发生的位置来将数组拆分为相同形状的数组。

  • 水平分割: 'hsplit()'函数沿轴参数 = 1 分割数组。'numpy.hsplit'等效于轴参数 = 1'split' ,无论数组维度如何,数组始终沿第二个轴分割.此函数将一个数组水平拆分为多个子数组(按列)。

    句法:

    numpy.hsplit(ary, indices_or_sections)

    例子:

    # Horizontal array splitting using np.hsplit()
    import numpy as np
      
      
    # Making of  a 3x3 array
    a = np.arange(9).reshape(3, 3)
      
    # Horizontal splitting of array 
    # 'a' using np.hsplit().
    print("The array {} gets splitted \
    horizontally to form {} ".format(a, np.hsplit(a, 3)))
      
    # Horizontal splitting of array 'a' 
    # using 'split' with axis parameter = 1.
    print("The array {} gets splitted \
    horizontally to form {} ".format(a, np.split(a, 3, 1)))
    

    输出:

    The array [[0 1 2]
     [3 4 5]
     [6 7 8]] gets splitted horizontally to form [array([[0],
           [3],
           [6]]), array([[1],
           [4],
           [7]]), array([[2],
           [5],
           [8]])] 
    The array [[0 1 2]
     [3 4 5]
     [6 7 8]] gets splitted horizontally to form [array([[0],
           [3],
           [6]]), array([[1],
           [4],
           [7]]), array([[2],
           [5],
           [8]])]
  • 垂直分割: 'vsplit()'函数沿轴参数 = 0 分割数组。'numpy.vsplit'等效于轴参数 = 0'split' 。此函数将一个数组垂直(按行)拆分为多个子数组。
    numpy.vsplit(ary, indices_or_sections)

    例子:

    import numpy as np
      
      
    # Making of  a 3x3 array
    a = np.arange(9).reshape(3, 3)
      
    # Vertical splitting of array 'a'
    # using np.vsplit().
    print("The array {} gets splitted \
    vertically to form {} ".format(a, np.vsplit(a, 3)))
      
    # Vertical splitting of array 'a' 
    # using 'split' with axis parameter = 0.
    print("The array {} gets splitted \
    vertically to form {} ".format(a, np.split(a, 3, 0)))
    

    输出:

  • 深度拆分:它将阵列沿第三轴(深度)拆分为多个子阵列。
    numpy.dsplit(ary, indices_or_sections)

    例子:

    import numpy as np
      
      
    # Making of  a 3x3x3 array.
    b = np.arange(27).reshape(3, 3, 3)
      
    # Depth-wise splitting of array
    # 'b' using np.dsplit().
    print("The array {} gets splitted \
    depth-wise to form {}".format(b, np.dsplit(b, 3)))
    

    输出: