首页 > 编程笔记 > Python笔记

NumPy分割数组函数(3个)

在 NumPy 中,分割数组的操作可以通过多种函数来实现,以下是一些常用的数组分割函数:

1) split() 函数用于沿指定轴将数组对象分割为子数组对象,其语法格式如下:
split(ary,indices_or_sections,axis)

2) hsplit() 函数用于沿 1 轴将数组对象分割为子数组对象,其语法格式如下:
hsplit(ary,indices_or_sections)

3) vsplit() 函数用于沿 0 轴将数组对象分割为子数组对象,需要注意的是,该函数不可用于一维数组对象,其语法格式如下:
vsplit(ary,indices_or_sections)

示例代码如下:
import numpy as np

# 一维数组对象
a = np.array([1, 2, 3, 4, 5, 6])
print(np.split(a, 3))
print('==========================')
print(np.hsplit(a, [1, 4]))
print('==========================')

# 二维数组对象
b = np.array([[1, 2, 3, 4],
              [5, 6, 7, 8],
              [9, 10, 11, 12],
              [13, 14, 15, 16]])
print(np.split(b, 2))
print('==========================')
print(np.hsplit(b, [1, 3]))
print('==========================')
print(np.vsplit(b, 2))
print('==========================')

# 三维数组对象
c = np.array([[[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, 30, 31, 32],
               [33, 34, 35, 36]]])
print(np.split(c, 3))
print('==========================')
print(np.hsplit(c, [1, 3]))
print('==========================')
print(np.vsplit(c, 3))
运行结果为:
[array([1, 2, 3]), array([4, 5, 6])]
==========================
[array([1, 2]), array([3, 4, 5, 6])]
==========================
[array([[ 1,  2,  3,  4]), array([[ 5,  6,  7,  8])], array([[ 9, 10, 11, 12]), array([[13, 14, 15, 16])])]
==========================
[array([[ 1,  2]), array([[ 5,  6,  7,  8])], array([[ 9, 10, 11, 12])], array([[13, 14, 15, 16])])]
==========================
[array([[ 1,  2,  3,  4]), array([[ 5,  6,  7,  8])], array([[ 9, 10, 11, 12]])]
==========================
[array([[[ 1,  2,  3,  4], [ 5,  6,  7,  8], [ 9, 10, 11, 12]]), array([[[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]), array([[[25, 26, 27, 28], [29, 30, 31, 32], [33, 34, 35, 36]])])]
==========================
[array([[[ 1,  2,  3,  4], [ 5,  6,  7,  8]], array([[ 9, 10, 11, 12], [13, 14, 15, 16]], array([[17, 18, 19, 20], [21, 22, 23, 24]]), array([[[25, 26, 27, 28], [29, 30, 31, 32], [33, 34, 35, 36]])))]
==========================
[array([[[ 1,  2,  3,  4], [ 5,  6,  7,  8], [ 9, 10, 11, 12]]), array([[[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]])]

相关文章