numpy.split() 是用于将一个数组沿指定的轴分割成多个子数组的方法。它的基本用法是将一个大的数组拆分成多个小的数组。如分割后的子数组大小不一致,且没有指定自定义索引位置,numpy.split 将抛出 ValueError 异常。要确保分割时数组的大小可以均匀分配或按照指定的索引进行分割。本文主要介绍一下NumPy中split方法的使用。

numpy.split

numpy.split(ary, indices_or_sections, axis=0)     [source]

将数组拆分为多个子数组,作为ary的视图。

参数 :

aryndarray

数组可分为子数组。

indices_or_sections :int 或 1-D array

如果indexs_or_sections是整数N,

则该数组将沿轴分为N个相等的数组。

 如果无法进行此类拆分,则会引发错误。 

如果indexs_or_sections是一维排序的整数数组,

则条目指示沿轴在哪里拆分该数组。 

例如,对于axis = 0[2,3]

将导致 

  • ary [:2] 
  • ary [2:3] 
  • ary [3:] 

如果索引沿轴超出数组的维数,

则将相应返回一个空的子数组。

axisint, 可选

沿其分割的轴,默认为0

返回值 :

sub-arrays :ndarrays的list

子数组列表,以查看ary。

Raises :

ValueError

如果indices_or_sections以整数的形式给出,

但是分割不会导致相等的分割。

例子

1)按照指定的数量分割数组

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
# 将数组分成4个等大小的子数组
result = np.split(arr, 4)  
print(result)

2)根据索引分割数组

import numpy as np


arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
# 在索引3和索引5处分割
result = np.split(arr, [3, 5])  
print(result)

3)沿着列方向分割二维数组

import numpy as np


arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
 # 沿着列方向分割成3个子数组
result = np.split(arr, 3, axis=1) 
print(result)

4)分割不等大小的子数组

import numpy as np


arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
# 在索引2和索引5处分割
result = np.split(arr, [2, 5])  
print(result)

推荐文档

相关文档

大家感兴趣的内容

随机列表