numpy分割数组

numpy学习专题

十四、numpy分割数组

分割数组

split()

原型:numpy.split(array,indices_or_setctions,axis=0)
作用:函数沿特定的轴将数组分割为子数组
参数                                说明
array                             被分割的数组
indices_or_sections              是一个整数,就用该数平均切分,如果是一个数组,为沿轴切分的位置(左开右闭)
axis                             沿着那个维度进行切向,默认为0,横向切分,为1时,纵向切分
import numpy as np
arr = np.arange(1,9).reshape(4,2)
print(arr,"\n")
print(np.split(arr,2),"\n")
print(np.split(arr,4),"\n")
print(np.split(arr,2,1),"\n")
print(np.split(arr,[1,2]),"\n")

arr2 = np.arange(1,10)
print(np.split(arr2,[3,8]))
[[1 2]
 [3 4]
 [5 6]
 [7 8]] 

[array([[1, 2],
       [3, 4]]), array([[5, 6],
       [7, 8]])] 

[array([[1, 2]]), array([[3, 4]]), array([[5, 6]]), array([[7, 8]])] 

[array([[1],
       [3],
       [5],
       [7]]), array([[2],
       [4],
       [6],
       [8]])] 

[array([[1, 2]]), array([[3, 4]]), array([[5, 6],
       [7, 8]])] 

[array([1, 2, 3]), array([4, 5, 6, 7, 8]), array([9])]

hsplit()

用于竖直分割数组,通过指定返回相同形状的数组数量来拆分原数组
import numpy as np
arr = np.arange(1,9).reshape(2,4)
print(arr,"\n")
print(np.hsplit(arr,4),"\n")
print(np.hsplit(arr,2),"\n")

[[1 2 3 4]
 [5 6 7 8]] 

[array([[1],
       [5]]), array([[2],
       [6]]), array([[3],
       [7]]), array([[4],
       [8]])] 

[array([[1, 2],
       [5, 6]]), array([[3, 4],
       [7, 8]])] 

vsplit()

用于竖直分割数组,通过指定返回相同形状的数组数量来拆分原数组
import numpy as np
arr = np.arange(1,9).reshape(4,2)
print(arr,"\n")
print(np.vsplit(arr,4),"\n")
print(np.vsplit(arr,2),"\n")

[[1 2]
 [3 4]
 [5 6]
 [7 8]] 

[array([[1, 2]]), array([[3, 4]]), array([[5, 6]]), array([[7, 8]])] 

[array([[1, 2],
       [3, 4]]), array([[5, 6],
       [7, 8]])] 

一定要支持作者哦

你可能感兴趣的:(numpy)