1. 程式人生 > >Python資料處理之(八)Numpy array分割

Python資料處理之(八)Numpy array分割

一、建立資料

匯入模組並建立34列的Array

>>> import numpy as np
>>> A=np.arange(12).reshape((3,4))
>>> print(A)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

二、縱向分割

>>> print(np.split(A,2,axis=1))
[array([[0, 1],
       [4, 5],
       [8, 9]]), array([[ 2,  3],
       [
6, 7], [10, 11]])]

三、橫向分割

>>> print(np.split(A,3,axis=0))
[array([[0, 1, 2, 3]]), array([[4, 5, 6, 7]]), array([[ 8,  9, 10, 11]])]

四、錯誤的分割

例子中的Array是3行4列的,如果要分割必須要等量分割,否則報錯。例如:下面這個按行分割就會報錯:

>>> print(np.split(A,2,axis=0))
Traceback (most recent call last):
  File "D:\Users\hupo\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\lib\shape_base.py"
, line 778, in split len(indices_or_sections) TypeError: object of type 'int' has no len() During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<pyshell#56>", line 1, in <module> print(np.split(A,2,axis=0)) File "D:\Users\hupo\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\lib\shape_base.py"
, line 784, in split 'array split does not result in an equal division') ValueError: array split does not result in an equal division

五、不等量分割

為了解決上邊的問題,可以採用下面這種不等量分割的方法:

>>> print(np.array_split(A,2,axis=0))
[array([[0, 1, 2, 3],
       [4, 5, 6, 7]]), array([[ 8,  9, 10, 11]])]

六、其他分割方法

numpy中還有np.vsplit()np.hsplit()方法可以用

>>> print(np.vsplit(A,3))
[array([[0, 1, 2, 3]]), array([[4, 5, 6, 7]]), array([[ 8,  9, 10, 11]])]
>>> print(np.hsplit(A,2))
[array([[0, 1],
       [4, 5],
       [8, 9]]), array([[ 2,  3],
       [ 6,  7],
       [10, 11]])]

np.vsplit(A,3)等價於np.split(A,3,axis=0)
np.hsplit(A,2)等價於np.split(A,2,axis=1)
下面這種表示更好理解:
橫向分割:從左到右分割(hsplit,axis=1)
縱向分割:從上到下分割(vsplit,axis=0)