numpy.split
numpy.split(ary, indices_or_sections, axis=0) [source]
将数组拆分为多个子数组,作为ary的视图。
参数 : | ary : 数组可分为子数组。 indices_or_sections :int 或 1-D array 如果indexs_or_sections是整数N, 则该数组将沿轴分为N个相等的数组。 如果无法进行此类拆分,则会引发错误。 如果indexs_or_sections是一维排序的整数数组, 则条目指示沿轴在哪里拆分该数组。 例如,对于 将导致
如果索引沿轴超出数组的维数, 则将相应返回一个空的子数组。 axis : 沿其分割的轴,默认为 |
返回值 : | sub-arrays :ndarrays的list 子数组列表,以查看ary。 |
Raises : | ValueError 如果indices_or_sections以整数的形式给出, 但是分割不会导致相等的分割。 |
例子
1)按照指定的数量分割数组
import numpy as np arr = np.array([1, 2, 3, 4, 5, 6, 7, 8]) # 将数组分成4个等大小的子数组 result = np.split(arr, 4) print(result)
2)根据索引分割数组
import numpy as np arr = np.array([1, 2, 3, 4, 5, 6, 7, 8]) # 在索引3和索引5处分割 result = np.split(arr, [3, 5]) print(result)
3)沿着列方向分割二维数组
import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # 沿着列方向分割成3个子数组 result = np.split(arr, 3, axis=1) print(result)
4)分割不等大小的子数组
import numpy as np arr = np.array([1, 2, 3, 4, 5, 6, 7, 8]) # 在索引2和索引5处分割 result = np.split(arr, [2, 5]) print(result)