@
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中對數組進行切分及一些基本概念
碼字不易,如果您覺得有幫助,麻煩點個贊再走唄~