【Numpy】拆分数组

文章目录

  • 前言
  • 1. split
  • 2. array_split
  • 3. dsplit
  • 4. hsplit
  • 5. vsplit
  • Reference

前言

本篇总结、介绍Numpy数组(ndarray)的基本操作之一——拆分数组 [1]。

1. split

numpy.split(ary, indices_or_sections, axis=0):将一个数组拆分为多个子数组,每个子数组都是原始数组的视图

  • ary:类数组。待拆分数组
  • indices_or_sections:整数或一维类数组
    • 整数:例如n,表示数组ary将沿指定的轴axis拆分为n个相等的数组。如果该拆分不可行,那么会引起错误
    • 一维类数组(如列表、元组):指示沿着指定的轴axis拆分的位置。如numpy.split(ary,[2,3], axis=0)将返回[ary[:2], ary[2:3], ary[3:]]
  • axis:整数型,可选参数
>>> 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]])]

2. array_split

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

3. dsplit

numpy.dsplit(ary, indices_or_sections):沿第三个轴将一个数组拆分为多个子数组(深度优先)

等同于numpy.split(ary, indices_or_sections,axis=2)。具体请参考numpt.split。

4. hsplit

numpy.hsplit(ary, indices_or_sections):沿水平方向将一个数组拆分为多个子数组(列优先)

等同于numpy.split(ary, indices_or_sections,axis=1)。具体请参考numpt.split。

5. vsplit

numpy.vsplit(ary, indices_or_sections):沿垂直方向将一个数组拆分为多个子数组(行优先)

Reference

[1]: https://numpy.org/doc/stable/reference/routines.array-manipulation.html

你可能感兴趣的:(Python基础,Numpy基础,python,numpy,数组)