@
NumPy(Numerical Python) 是 Python 语言的一个扩展程序库,支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。np.split()函数的作用是将一个数组拆分为多个子数组,跟Tensorflow中的slice()函数有点类似,但是np.split()函数返回的是多个数组,tf.slice()函数返回的则是被切取的一个张量,区别还是挺大的。
1.官方注释
官方的注释如下:
"""
Split an array into multiple sub-arrays.
Parameters
----------
ary : ndarray
Array to be divided into sub-arrays.
indices_or_sections : int or 1-D array
If `indices_or_sections` is an integer, N, the array will be divided
into N equal arrays along `axis`. If such a split is not possible,
an error is raised.
If `indices_or_sections` is a 1-D array of sorted integers, the entries
indicate where along `axis` the array is split. For example,
``[2, 3]`` would, for ``axis=0``, result in
- ary[:2]
- ary[2:3]
- ary[3:]
If an index exceeds the dimension of the array along `axis`,
an empty sub-array is returned correspondingly.
axis : int, optional
The axis along which to split, default is 0.
Returns
-------
sub-arrays : list of ndarrays
A list of sub-arrays.
Raises
------
ValueError
If `indices_or_sections` is given as an integer, but
a split does not result in equal division.
See Also
--------
array_split : Split an array into multiple sub-arrays of equal or
near-equal size. Does not raise an exception if
an equal division cannot be made.
hsplit : Split array into multiple sub-arrays horizontally (column-wise).
vsplit : Split array into multiple sub-arrays vertically (row wise).
dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
concatenate : Join a sequence of arrays along an existing axis.
stack : Join a sequence of arrays along a new axis.
hstack : Stack arrays in sequence horizontally (column wise).
vstack : Stack arrays in sequence vertically (row wise).
dstack : Stack arrays in sequence depth wise (along third dimension).
除了split函数外,还有array_split函数,hsplit函数(用于水平分割),vsplit函数(用于垂直分割)等等。spli函数只能用于均等分割,如果不能均等分割则会报错:array split does not result in an equal division
。而array_split则全能一点,可以用于不均等分割。
2.参数解释
def split(ary, indices_or_sections, axis=0):
...
return res
- ary
ary的类型为ndarray(n维数组),表示待分割的原始数组 - indices_or_sections
indices_or_sections的类型为int或者一维数组,表示一个索引,也就是切的位置所在。indices_or_sections的值如果是一个整数的话,就用这个数平均分割原数组。indices_or_sections的值如果是一个数组的话,就以数组中的数字为索引切开,这个不是太好理解,待会看例子应该就容易理解了。 - axis
axis的类型为int,表示的是沿哪个维度切,默认为0表示横向切,为1时表示纵向切。
3.例子
- 例1
A = np.arange(36).reshape((2, 2, 9))
print(A)
print(A.shape)
[A1, A2, A3] = np.split(A, [3, 6], axis=2)
C = np.split(A, 3, axis=2)
- 例2
参考
[1] NumPy 教程
[2] numpy.split()函数
[3] NumPy中对数组进行切分及一些基本概念
码字不易,如果您觉得有帮助,麻烦点个赞再走呗~