本篇总结、介绍Numpy数组(ndarray)的基本操作之一——拆分数组 [1]。
numpy.split(ary, indices_or_sections, axis=0):将一个数组拆分为多个子数组,每个子数组都是原始数组的视图
>>> arr = np.arange(8)
>>> arr
array([0, 1, 2, 3, 4, 5, 6, 7])
>>> np.split(arr,2)
[array([0, 1, 2, 3]), array([4, 5, 6, 7])]
>>> np.split(arr,3)
ValueError: array split does not result in an equal division
>>> np.split(arr,[2,3])
[array([0, 1]), array([2]), array([3, 4, 5, 6, 7])]
>>> arr = arr.reshape(4,2)
>>> np.split(arr,2)
[array([[0, 1],
[2, 3]]), array([[4, 5],
[6, 7]])]
>>> np.split(arr,[2,3])
[array([[0, 1],
[2, 3]]), array([[4, 5]]), array([[6, 7]])]
numpy.array_split(ary, indices_or_sections, axis=0):将一个数组拆分为多个子数组
numpy.array_split和numpy.split基本一样,唯一的区别在于,当indices_or_sections为整数,且无法沿着指定的轴axis将数组ary拆分成相等的数组时,numpy.split会报错而numpy.array_split可以成功执行。
>>> arr = np.arange(8)
>>> arr
array([0, 1, 2, 3, 4, 5, 6, 7])
array([0, 1, 2, 3, 4, 5, 6, 7])
>>> np.array_split(arr,3)
[array([0, 1, 2]), array([3, 4, 5]), array([6, 7])]
>>> np.split(arr,3)
ValueError: array split does not result in an equal division
numpy.dsplit(ary, indices_or_sections):沿第三个轴将一个数组拆分为多个子数组(深度优先)
等同于numpy.split(ary, indices_or_sections,axis=2)。具体请参考numpt.split。
numpy.hsplit(ary, indices_or_sections):沿水平方向将一个数组拆分为多个子数组(列优先)
等同于numpy.split(ary, indices_or_sections,axis=1)。具体请参考numpt.split。
numpy.vsplit(ary, indices_or_sections):沿垂直方向将一个数组拆分为多个子数组(行优先)