有合并,就有分割。
本节主要讲述如何通过numpy对数组进行横向/纵向分割。横向/纵向分割数组
首先创建一个6行4列的数组,然后我们对此数组按照横向进行切割,分成3块,这样每块应该有2行,见例子:
import numpy as npa = 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份,如果我们不想分割成等分的,可以写成如下的方式:
import numpy as npa = np.arange(24).reshape(6, 4)print("a=")print(a)print(np.split(a, [3, 5], 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], [ 8, 9, 10, 11]]), array([[12, 13, 14, 15], [16, 17, 18, 19]]), array([[20, 21, 22, 23]])]
这里[3, 5]进行分割的意思是在第3行和第5行出进行切割。
同理,我们如果把axis设置为1,则可以按照列进行分割,例如,我们把上面的6行4列的数据分割成2列:
import numpy as npa = np.arange(24).reshape(6, 4)print("a=")print(a)print(np.split(a, 2, axis=1))
输出:
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]])]
水平分割hsplit
我们也可以用单独的水平或垂直分割函数对数组进行分割。
例如把数组水平分割成两列:import numpy as npa = 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]])]
垂直分割vsplit
例如:
import numpy as npa = 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]])]