Python—Numpy学习笔记(七)array的分割

注:本系类笔记采用的是Python3.5X版本,编程环境为Windows64位下的Anaconda
所有代码部分均为连续的,“结果”为在jupyter分步运行结果

代码部分:

import numpy as np
arr1 = np.arange(12).reshape((3,4))
print(arr1)

结果:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]

arr2,arr3 = np.split(arr1,2,axis=1)#按列方向分割,分成2份
print(arr2)
print(arr3)

结果:
[[0 1]
[4 5]
[8 9]]
[[ 2 3]
[ 6 7]
[10 11]]

arr4,arr5,arr6 = np.split(arr1,3,axis=0)#按行方向分割,分成3份
print(arr4)
print(arr5)
print(arr6)

结果:
[[0 1 2 3]]
[[4 5 6 7]]
[[ 8 9 10 11]]

arr2,arr3,arr4 = np.split(arr1,3,axis=1)#按列方向分割,分成3份
print(arr2)
print(arr3)
print(arr4)

结果:(报错,无法切分成3个相同大小的3部分)

TypeError Traceback (most recent call last)
F:\Anaconda3\lib\site-packages\numpy\lib\shape_base.py in split(ary, indices_or_sections, axis)
501 try:
--> 502 len(indices_or_sections)
503 except TypeError:

TypeError: object of type 'int' has no len()

During handling of the above exception, another exception occurred:

ValueError Traceback (most recent call last)
in ()
----> 1 arr2,arr3,arr4 = np.split(arr1,3,axis=1)#水平方向分割,分成3份
2 print(arr2)
3 print(arr3)
4 print(arr4)

F:\Anaconda3\lib\site-packages\numpy\lib\shape_base.py in split(ary, indices_or_sections, axis)
506 if N % sections:
507 raise ValueError(
--> 508 'array split does not result in an equal division')
509 res = array_split(ary, indices_or_sections, axis)
510 return res

ValueError: array split does not result in an equal division

arr7,arr8,arr9 = np.array_split(arr1,3,axis=1)#按列方向分割,分成3份,不等分割
print(arr7)
print(arr8)
print(arr9)

结果:
[[0 1]
[4 5]
[8 9]]
[[ 2]
[ 6]
[10]]
[[ 3]
[ 7]
[11]]

——————————————————————
以下是分割的另外一种方法

arrv1,arrv2,arrv3 = np.vsplit(arr1,3)#按行分割成3部分
print(arrv1)
print(arrv2)
print(arrv3)

结果:
[[0 1 2 3]]
[[4 5 6 7]]
[[ 8 9 10 11]]

arrh1,arrh2 = np.hsplit(arr1,2)#水平分割成2部分
print(arrh1)
print(arrh2)

结果:
[[0 1]
[4 5]
[8 9]]
[[ 2 3]
[ 6 7]
[10 11]]

你可能感兴趣的:(Python—Numpy学习笔记(七)array的分割)