有合併,就有分割。
本節主要講述如何經過numpy對數組進行橫向/縱向分割。python
首先建立一個6行4列的數組,而後咱們對此數組按照橫向進行切割,分紅3塊,這樣每塊應該有2行,見例子:數組
import numpy as np a = np.arange(24).reshape(6, 4) print("a=") print(a) print(np.split(a, 3, axis=0))
輸出爲:函數
a= [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15] [16 17 18 19] [20 21 22 23]] [array([[0, 1, 2, 3], [4, 5, 6, 7]]), array([[ 8, 9, 10, 11], [12, 13, 14, 15]]), array([[16, 17, 18, 19], [20, 21, 22, 23]])]
上面的分割中把數組分紅了等分的3份,若是咱們不想分割成等分的,能夠寫成以下的方式:code
import numpy as np a = np.arange(24).reshape(6, 4) print("a=") print(a) print(np.split(a, [3, 5], axis=0))
輸出爲:it
a= [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15] [16 17 18 19] [20 21 22 23]] [array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]), array([[12, 13, 14, 15], [16, 17, 18, 19]]), array([[20, 21, 22, 23]])]
這裏[3, 5]進行分割的意思是在第3行和第5行出進行切割。class
同理,咱們若是把axis設置爲1,則能夠按照列進行分割,例如,咱們把上面的6行4列的數據分割成2列:import
import numpy as np a = np.arange(24).reshape(6, 4) print("a=") print(a) print(np.split(a, 2, axis=1))
輸出:numpy
a= [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15] [16 17 18 19] [20 21 22 23]] [array([[ 0, 1], [ 4, 5], [ 8, 9], [12, 13], [16, 17], [20, 21]]), array([[ 2, 3], [ 6, 7], [10, 11], [14, 15], [18, 19], [22, 23]])]
咱們也能夠用單獨的水平或垂直分割函數對數組進行分割。
例如把數組水平分割成兩列:im
import numpy as np a = np.arange(24).reshape(6, 4) print("a=") print(a) print(np.hsplit(a, 2))
輸出:數據
a= [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15] [16 17 18 19] [20 21 22 23]] [array([[ 0, 1], [ 4, 5], [ 8, 9], [12, 13], [16, 17], [20, 21]]), array([[ 2, 3], [ 6, 7], [10, 11], [14, 15], [18, 19], [22, 23]])]
例如:
import numpy as np a = np.arange(24).reshape(6, 4) print("a=") print(a) print(np.vsplit(a, 2))
輸出爲:
a= [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15] [16 17 18 19] [20 21 22 23]] [array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]), array([[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]])]