读书笔记 numpy入门 第2章 数组分裂

np.split

Split an array into multiple sub-arrays

向以上函数传递一个索引列表作为参数,索引列表记录的是分裂点位置:

1
2
3
4
5
x = [1, 2, 3, 99, 99, 3, 2, 1]
x1, x2, x3 = np.split(x, [3, 5])
print(x1, x2, x3)

>>> [1 2 3] [99 99] [3 2 1]

https://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html

参数:

  • ary
  • indices or sections
  • axis
1
2
3
>>> x = np.arange(9.0)
>>> np.split(x, 3)
>>> array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7., 8.])]
1
2
3
4
5
6
7
>>> x = np.arange(8.0)
>>> np.split(x, [3, 5, 6, 10])
>>>[array([ 0., 1., 2.]),
array([ 3., 4.]),
array([ 5.]),
array([ 6., 7.]),
array([], dtype=float64)]

np.vsplit和np.hsplit

N 分裂点会得到 N + 1 个子数组。

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
27
28
29
grid = np.arange(16).reshape((4, 4))
grid

>>> array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])

upper, lower = np.vsplit(grid, [2])
print(upper)
print(lower)

>>>[[0 1 2 3]
[4 5 6 7]]
[[ 8 9 10 11]
[12 13 14 15]]

left, right = np.hsplit(grid, [2])
print(left)
print(right)

>>>[[ 0 1]
[ 4 5]
[ 8 9]
[12 13]]
[[ 2 3]
[ 6 7]
[10 11]
[14 15]]

https://docs.scipy.org/doc/numpy/reference/generated/numpy.vsplit.html

https://docs.scipy.org/doc/numpy/reference/generated/numpy.hsplit.html

np.dsplit

https://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html

1
2
3
4
>>> x = np.arange(9.0)
>>> np.split(x, 3)

>>> [array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7., 8.])]
1
2
3
4
5
6
7
8
9
>>> x = np.arange(8.0)
>>> np.split(x, [3, 5, 6, 10])


>>>[array([ 0., 1., 2.]),
array([ 3., 4.]),
array([ 5.]),
array([ 6., 7.]),
array([], dtype=float64)]