기록하는 습관

[Numpy] 006. 배열 자르기 (Split) 본문

Python/Numpy

[Numpy] 006. 배열 자르기 (Split)

Avalla 2023. 8. 8. 00:32

배열 자르기

import numpy as np

 

np.split(배열, 기준, 축)

Signature: np.split(ary, indices_or_sections, axis=0)

Docstring:

Split an array into multiple sub-arrays as views into ary.

array = np.array(range(10))
a1, a2, a3 = np.split(array, [3,6], axis=0)
print( "array :\n", array )
print( a1, a2, a3 )
array :
 [0 1 2 3 4 5 6 7 8 9]
[0 1 2] [3 4 5] [6 7 8 9]
array = np.array(range(20)).reshape(4,5)
upper, lower = np.split(array, [3], axis=0)
print( "array :\n", array )
print( "upper :\n", upper)
print( "lower :\n", lower)
array :
 [[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]]
upper :
 [[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]
lower :
 [[15 16 17 18 19]]
array = np.array(range(20)).reshape(4,5)
left, right = np.split(array, [3], axis=1)
print( "array :\n", array )
print( "left :\n", left)
print( "right :\n", right)
array :
 [[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]]
left :
 [[ 0  1  2]
 [ 5  6  7]
 [10 11 12]
 [15 16 17]]
right :
 [[ 3  4]
 [ 8  9]
 [13 14]
 [18 19]]

3차원 예시는 아래와 같다.

array = np.array(range(18)).reshape(2,3,3)
a1, a2 = np.split(array, [1], axis=0)
print( "array :\n", array, array.shape, end="\n_____split_____\n" )
print( "a1 :\n", a1, a1.shape, end="\n_______________\n" )
print( "a2 :\n", a2, a2.shape )
array :
 [[[ 0  1  2]
  [ 3  4  5]
  [ 6  7  8]]

 [[ 9 10 11]
  [12 13 14]
  [15 16 17]]] (2, 3, 3)
_____split_____
a1 :
 [[[0 1 2]
  [3 4 5]
  [6 7 8]]] (1, 3, 3)
_______________
a2 :
 [[[ 9 10 11]
  [12 13 14]
  [15 16 17]]] (1, 3, 3)
array = np.array(range(18)).reshape(2,3,3)
a1, a2 = np.split(array, [1], axis=1)
print( "array :\n", array, array.shape, end="\n_____split_____\n" )
print( "a1 :\n", a1, a1.shape, end="\n_______________\n" )
print( "a2 :\n", a2, a2.shape )
array :
 [[[ 0  1  2]
  [ 3  4  5]
  [ 6  7  8]]

 [[ 9 10 11]
  [12 13 14]
  [15 16 17]]] (2, 3, 3)
_____split_____
a1 :
 [[[ 0  1  2]]

 [[ 9 10 11]]] (2, 1, 3)
_______________
a2 :
 [[[ 3  4  5]
  [ 6  7  8]]

 [[12 13 14]
  [15 16 17]]] (2, 2, 3)
array = np.array(range(18)).reshape(2,3,3)
a1, a2 = np.split(array, [1], axis=2)
print( "array :\n", array, array.shape, end="\n_____split_____\n" )
print( "a1 :\n", a1, a1.shape, end="\n_______________\n" )
print( "a2 :\n", a2, a2.shape )
array :
 [[[ 0  1  2]
  [ 3  4  5]
  [ 6  7  8]]

 [[ 9 10 11]
  [12 13 14]
  [15 16 17]]] (2, 3, 3)
_____split_____
a1 :
 [[[ 0]
  [ 3]
  [ 6]]

 [[ 9]
  [12]
  [15]]] (2, 3, 1)
_______________
a2 :
 [[[ 1  2]
  [ 4  5]
  [ 7  8]]

 [[10 11]
  [13 14]
  [16 17]]] (2, 3, 2)