在NumPy中拆分数组
数组分割可以是垂直的,水平的,或深度的。我们可以分别使用函数hsplit()、vsplit()和dsplit()进行同样的操作。我们可以通过指明分割后的位置将数组分割成相同形状的数组。
- 水平拆分。’hsplit()’函数沿参数=1的轴分割一个数组。’numpy.hsplit’相当于轴参数=1的’split’,数组总是沿第二个轴分割,而不考虑数组的尺寸。这个函数将一个数组水平地分割成多个子数组(column-wise)。
语法:
numpy.hsplit(ary, indices_or_sections)
示例:
# Horizontal array splitting using np.hsplit()
import numpy as np
# Making of a 3x3 array
a = np.arange(9).reshape(3, 3)
# Horizontal splitting of array
# 'a' using np.hsplit().
print("The array {} gets splitted \
horizontally to form {} ".format(a, np.hsplit(a, 3)))
# Horizontal splitting of array 'a'
# using 'split' with axis parameter = 1.
print("The array {} gets splitted \
horizontally to form {} ".format(a, np.split(a, 3, 1)))
输出:
The array [[0 1 2]
[3 4 5]
[6 7 8]] gets splitted horizontally to form [array([[0],
[3],
[6]]), array([[1],
[4],
[7]]), array([[2],
[5],
[8]])]
The array [[0 1 2]
[3 4 5]
[6 7 8]] gets splitted horizontally to form [array([[0],
[3],
[6]]), array([[1],
[4],
[7]]), array([[2],
[5],
[8]])]
- 垂直拆分。vsplit() “函数沿参数=0的轴分割一个数组。’numpy.vsplit’相当于轴参数=0的’split’。这个函数将一个数组垂直地分割成多个子数组(一行一列)。
numpy.vsplit(ary, indices_or_sections)
示例:
import numpy as np
# Making of a 3x3 array
a = np.arange(9).reshape(3, 3)
# Vertical splitting of array 'a'
# using np.vsplit().
print("The array {} gets splitted \
vertically to form {} ".format(a, np.vsplit(a, 3)))
# Vertical splitting of array 'a'
# using 'split' with axis parameter = 0.
print("The array {} gets splitted \
vertically to form {} ".format(a, np.split(a, 3, 0)))
输出:
数组[[0 1 2]]
[3 4 5]
[6 7 8]]被垂直分割成[数组([[0, 1, 2]]), 数组([[3, 4, 5]]), 数组([[6, 7, 8]])
数组[[0 1 2]]
[3 4 5]
[6 7 8]]被垂直分割成[数组([[0, 1, 2]]), 数组([[3, 4, 5]]), 数组([[6, 7, 8]])
- 深度分割。它沿第三轴(深度)将阵列分成多个子阵列。
numpy.dsplit(ary, indices_or_sections)
示例:
import numpy as np
# Making of a 3x3x3 array.
b = np.arange(27).reshape(3, 3, 3)
# Depth-wise splitting of array
# 'b' using np.dsplit().
print("The array {} gets splitted \
depth-wise to form {}".format(b, np.dsplit(b, 3)))
输出:
The array [[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]]
[[ 9 10 11]
[12 13 14]
[15 16 17]]
[[18 19 20]
[21 22 23]
[24 25 26]]] gets splitted depth-wise to form [array([[[ 0],
[ 3],
[ 6]],
[[ 9],
[12],
[15]],
[[18],
[21],
[24]]]), array([[[ 1],
[ 4],
[ 7]],
[[10],
[13],
[16]],
[[19],
[22],
[25]]]), array([[[ 2],
[ 5],
[ 8]],
[[11],
[14],
[17]],
[[20],
[23],
[26]]])]