Table of Contents

Python

Numpy Array 쪼개기

꼬꼬마코더 2024. 4. 20. 16:50
728x90

array3d.shape >>> (높이=2,행=3,열=4)

array3d
>>>
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]]])

 

 

 

 

 

1. array3d를 1부터 12까지, 13부터 24까지 위 아래로 쪼개고 싶다면?

vsplit (vertical split) axis=0을 기준

numpy.split(ary,indices_or_sections,axis=0) axis=1,2은 안된다

numpy.array_split(ary,indices_or_sections,axis=0) axis=1,2은 안된다

numpy.vsplit(aryindices_or_sections)

 

splitted_arrays = np.split(array3d, 2, axis=0)

print("Splitted Arrays along axis 0:")
for arr in splitted_arrays:
    print(arr, "\n")
>>>    
Splitted Arrays along axis 0:
[[[ 1  2  3  4]
  [ 5  6  7  8]
  [ 9 10 11 12]]] 

[[[13 14 15 16]
  [17 18 19 20]
  [21 22 23 24]]] 

   
print(splitted_arrays)
>>>
[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]]])]


print(splitted_arrays[0])
>>>
[[[ 1  2  3  4]
  [ 5  6  7  8]
  [ 9 10 11 12]]]


print(splitted_arrays[1])
>>>
[[[13 14 15 16]
  [17 18 19 20]
  [21 22 23 24]]]
vsplitted_arrays = np.vsplit(array3d, 2) #p.vsplit(array3d, 3)은 할 수 없다 
print(vsplitted_arrays)
>>>
vsplitted_arrays = np.vsplit(array3d, 2)
print(vsplitted_arrays)

 

 

2. 이번엔 array3d를 케이크 자르듯이 반을 가르고 싶다면?

dsplit (depth split) axis=2를 기준

 

numpy.dsplit(ary, indices_or_sections)  dsplit is equivalent to split with axis=2

array3d
>>>
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]]])

 

splitted_arrays = np.dsplit(array3d, 2)
        
print(splitted_arrays)
>>>
[array([[[ 1,  2],
        [ 5,  6],
        [ 9, 10]],

       [[13, 14],
        [17, 18],
        [21, 22]]]), array([[[ 3,  4],
        [ 7,  8],
        [11, 12]],

       [[15, 16],
        [19, 20],
        [23, 24]]])]
        
print(splitted_arrays[0])
>>>
[[[ 1  2]
  [ 5  6]
  [ 9 10]]

 [[13 14]
  [17 18]
  [21 22]]]
  
print(splitted_arrays[1])
>>>
[[[ 3  4]
  [ 7  8]
  [11 12]]

 [[15 16]
  [19 20]
  [23 24]]]

 

 

3. 이번엔 array3d를 1,2,3,4/ 5,6,7,8/ 9,10,11,12 이렇게 3조각으로 자르고 싶다면?

hsplit (horizontal split) axis=1를 기준

 

numpy.hsplit(aryindices_or_sections)

hsplitted_arrays = np.hsplit(array3d, 3)
print(hsplitted_arrays)
>>>
[array([[[ 1,  2,  3,  4]],

       [[13, 14, 15, 16]]]), array([[[ 5,  6,  7,  8]],

       [[17, 18, 19, 20]]]), array([[[ 9, 10, 11, 12]],

       [[21, 22, 23, 24]]])]

 

 

 

shape(vertical=높이, horizontal=행, depth=열) 기억해주세요

 

 

2024.04.20 - [Python] - Numpy Array를 쌓기