Yeonnnnny

[Numpy] 배열의 변경 본문

Python/Numpy

[Numpy] 배열의 변경

yeonny_do 2023. 11. 14. 00:26

■ np.reshape() / ndarray.reshape()

 

   - 원본 변경하지 않고 배열을 새로운 shape으로 수정함

   - 원본 배열의 요소의 개수가 변경할 모양의 매열 요소의 개수와 가르면 에러 발생 

 

 
import numpy as np

a = np.arange(6)
print(a)

b = a.reshape(3,2)
print(b)

print(a) # b의 생성에 의해 a가 변하지 않음

print('-'*30)

c=np.reshape(a,(1,6))
print(c)

d = np.reshape(a,(-1,2)) # 열의 크기만 2로 맞추고 행의 크기는 전체 요소 크기에 맞춰 알아서 지정함(-1)
print(d)
 

 

 

 

 

 

 

 
e = np.arange(1,11).reshape(2,5)
print(e)

print()

f = e.reshape((-1,2,1))  # 2행 1열의 요소의 크기에 맞게 다차원배열 생성
print(f)

print()

g =f.reshape(-1)  # -1의 의미는 행령의 값이 없으므로 요소를한 줄로 나타내게 됨(1차원 벡터)
print(g)
 

 

 

 

 

 


■ np.resize() / ndarray.resize()

 

    - 원본 배열을 새로운 shape으로 수정함

    - 대상 배열의 요소의 개수가 원래 배열과 동일하지 않으면 크기를 강제로 조정함

 

 
a = np.arange(12)
a.resize(3,4)
print(a)

print('-'*30)

b = np.resize(a,(3,4))
print(b)
print(a)

print('-'*30)

a.resize(4,4)
print(a)
 

 

 

 

 

 


■ ndarray.flatten() / ndarray.ravel()

 

     - 배열을 1차원으로 만듦

     - flatten : 배열을 복사해서 1차원으로 변경(원본에 영향을 미치지 않음)

     - ravel : 차원 변경X. 원본을 복사하는 것이 아니므로 메모리 낭비가 없음. 단, 값 수정 시 원본도 수정됨

 

 
a = np.arange(1,5).reshape(2,2)
print(a)

print(a.flatten())
 

 

 

 

 

 
a = np.arange(1,5).reshape(2,2)
r = a.ravel()
print(r)

print('-'*10)

a[1,1] = 5
print(a)

print('-'*10)

print(r)

 

 ※ 원본값 수정시 ravel로 생성된 배열의 값도 변경됨. ravel로 생성된 배열의 값을 바꾸면 원본값의 값이 변경됨

 

 

 

 


■ np.expand_dims()

 

    - 지정한 axis의 위치에 다차원 배열의 차원을 늘려줌

 

 
a = np.array([1,2])
print(a)
print(a.shape)
print('-'*20)


#1차원 벡터에 첫 번째 축(행 축)을 추가하여 2 앞에 1이 추가되어 (1,2)의 모양으로 확장됨
b = np.expand_dims(a,axis=0)
print(b)
print(b.shape)
print('-'*20)

c = np.expand_dims(a,axis=1)
print(c)
print(c.shape)

 

 

 

 
a = np.arange(1,7).reshape(2,3)
print(a)
print(a.shape)
print('-'*20)

# 2차원 > 3차원
# 원본의 어느 축에 새로운 축을 넣는지에 따라 모양 달라짐
# axis = 0 : 깊이 축으로 추가됨
# axis = 1 : 행 축으로 추가됨
# axis = 2 : 열 축으로 추가됨

b = np.expand_dims(a, axis=0) # 깊이 축으로
print(b)
print(b.shape)
print('-'*20)

c = np.expand_dims(a, axis=1) # 행 축으로
print(c)
print(c.shape)
print('-'*20)


d = np.expand_dims(a, axis=2) # 열 축으로
print(d)
print(d.shape)
print('-'*20)

 

 

 

 

 

 


■ np.newaxis를 이용해서 차원을 늘릴 수있음

 

 
a = np.arange(4)
print(a)
print(a.shape)
print('-'*20)

row_vect = a[np.newaxis,:]
print(row_vect)
print(row_vect.shape)
print('-'*20)

col_vect = a[:,np.newaxis]
print(col_vect)
print(col_vect.shape)
print('-'*20)

 

 

 

 

 


■ ndarray.astype()

   - 배열의 데이터타입을 변경

 

 
a = np.array([1,2,3])
print(a)
print(a.dtype)

a_float = a.astype(np.float32)
print(a_float)
print(a_float.dtype)
 

 

 

 


■ np.squeeze()

    : 차원 축소

 

 
a = np.array([[[0],[1],[2]]])
print(a)
print(a.shape)
print('-'*20)

b = np.squeeze(a)  # 디폴트 : 1차원 벡터로
print(b)
print(b.shape)
print('-'*20)

c = np.squeeze(a, axis=0)
print(c)
print(c.shape)
print('-'*20)

# valueError : 원본의 원소 개수와 일치되지 않기 때문
# d = np.squeeze(a, axis=1)
# print(d)

e = np.squeeze(a,axis=2)
print(e)
print(e.shape)
print('-'*20)

 

 

 

   - 1차원을 squeeze하면 ?

 
x = np.array([[1234]])
print(x)
print(x.shape)

print('-'*20)

y=np.squeeze(x)
print(y)
print(y.shape)  # 스칼라 값(단일값)으로 변경
 

 

 

 

 


■ np.concatenate()

 

   - 두 개 이상의 배열을 연결

   - 연결 수행 시, 차원의 수가 같아야 함

 

 
a =np.arange(1,5).reshape(2,2)
print(a)
print(a.shape)

print('-'*20)

b = np.array([5,6])
print(b)
print(b.shape)

print('-'*20)

print(np.concatenate((a, np.expand_dims(b,axis=0)))) # (2,)->(1,2)로 변경되어야 concatenate함수 적용 가능
 

 

 

 

 

  - 3개 이상의 배열도 concatenate 가능

 

 
a =np.arange(1,5).reshape(2,2)
b = np.array([[5,6]])
c = np.array([[7,8]])
d = np.concatenate((a,b,c))
print(d)
 

 

 

 

 

  - axis 인수를 설정하면 연결 발행을 정할 수 있음 (default : axis=0)

  - 행을 기준으로 연결할 때는 열의 개수가 일치해야 함

  - 열을 기준으로 연결할 때는 행의 개수가 일치해야 함

 

 
a =np.arange(1,5).reshape(2,2)
b = np.array([[5,6]])

e = np.concatenate((a,b.T),axis=1)
print(e)
 

 

 

'Python > Numpy' 카테고리의 다른 글

[Numpy] 배열 생성 - 3  (0) 2023.11.10
[Numpy] 배열 생성 - 2  (0) 2023.11.10
[Numpy] 배열 생성 - 1  (0) 2023.11.10
[Numpy] 기본 축의 개념 vs 행렬 연산 시 축의 개념  (0) 2023.11.10