NumPy数组的分割
在 NumPy 中,利用 split()、hsplit() 和 vsplit() 等函数可实现数组的分割操作。
split() 函数
该函数可沿特定的轴将数组分割为子数组。使用 split() 函数的方法如下:numpy.split(arr,indices_or_sections,axis)
其中,参数 arr 表示被分割的数组,indices_or_sections 表示从 arr 数组创建的大小相同的子数组的数量,可以为整数。如果此参数是一维数组,则该参数表示在 arr 数组中的分割点,arr 数组将按照分割点来分割数组。axis 表示返回数组中的轴,默认为 0,表示竖直方向分割,1 表示水平方向分割。hsplit() 函数
该函数是 split() 函数的特例,它是将数组沿着水平方向分割,即将一个数组按列分割为多个子数组。使用 hsplit() 函数的方法如下:numpy.hsplit(arr,indices_or_sections)
其中,参数 arr 表示被分割的数组,indices_or_sections 表示将 arr 数组创建为大小相同的子数组的数量。如果此参数是一维数组,则该参数表示在 arr 数组中的分割点,arr 数组将按照分割点来分割数组。vsplit()函数
该函数是 split() 函数的特例,它是将数组沿着竖直方向分割,即将一个数组按行分割为多个子数组。使用 vsplit() 函数的方法如下:numpy.vsplit(arr,indices_or_sections)
其中,参数 arr 表示被分割的数组;indices_or_sections 表示将 arr 数组创建为大小相同的子数组的数量。如果此参数是一维数组,则该参数表示在 arr 数组中的分割点,arr 数组将按照分割点来分割数组。数组的分割示例
数组的分割示例代码 example1 如下。# -*- coding: UTF-8 -*- import numpy as np arr1 = np.array([[1,2,3], [4,5,6]]) #创建数组arr1 print('第1个数组arr1:',arr1) arr2 =np.arange(9) #创建数组arr2 print('第2个数组arr2:',arr2) #使用split函数 print('将arr1数组竖直分割为2个大小相等的子数组:') print (np.split(arr1,2)) print('将arr1数组水平分割为3个大小相等的子数组:') print (np.split(arr1,3,1)) print('将arr2数组在一维数组中标明的位置分割:') print (np.split(arr2, [2, 5])) #使用hsplit函数和vsplit函数 print ('arr1数组水平分割:') print(np.hsplit(arr1,3)) print ('arr1数组竖直分割:') print(np.vsplit(arr1,2)) print ('arr2数组水平分割:') print (np.hsplit(arr2, [2, 5]))