[Python]numpy reshape

JONGBAO·2024년 1월 29일

1. reshape 함수

  • 배열과 차원을 변환해주는 함수
  • np.reshape(변경할 배열(리스트, 튜플, array 가능), 변경할 차원)
  • 배열.reshape(차원) -> 리스트, 튜플 불가능 (list or tuple has no attribute 'reshape')
a = [1,2,3,4,5,6,7,8]
b = (1,2,3,4,5,6,7,8)
np.reshape(a,(2,4))
>>>array([[1, 2, 3, 4],
          [5, 6, 7, 8]])
np.reshape(b,(2,4))
>>>array([[1, 2, 3, 4],
          [5, 6, 7, 8]])
          
np.array(a).reshape(2,4)
>>>array([[1, 2, 3, 4],
          [5, 6, 7, 8]])
np.array(b).reshape(2,4)
>>>array([[1, 2, 3, 4],
          [5, 6, 7, 8]])

2. reshape(-1,n), reshape(n,-1)

  • '-1' 위치의 차원은 남은 차원으로부터 추정하겠다는 의미
d = np.arange(12)
>>>array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
e = d.reshape(3,4)
>>>array([[ 0,  1,  2,  3],
          [ 4,  5,  6,  7],
          [ 8,  9, 10, 11]])

2-1. reshape(-1,n)

  • 행의 개수가 n값에 따라 자동으로 추정이 됨
e.reshape(-1,1) #열이 1개
>>>array([[ 0],
          [ 1],
          [ 2],
          [ 3],
          [ 4],
          [ 5],
          [ 6],
          [ 7],
          [ 8],
          [ 9],
          [10],
          [11]])
e.reshape(-1,3) #열이 3개
>>>array([[ 0,  1,  2],
          [ 3,  4,  5],
          [ 6,  7,  8],
          [ 9, 10, 11]])
  • 범위를 넘어가는 숫자값을 대입하면 에러 남 (여기서는 7이상)

2-2. reshape(n,-1)

  • 열의 개수가 n값에 따라 자동으로 추정이 됨
e.reshape(1,-1) #행이 1개
>>>array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11]])
e.reshape(3,-1) #행이 3개
>>>array([[ 0,  1,  2,  3],
          [ 4,  5,  6,  7],
          [ 8,  9, 10, 11]])
  • -1만 대입하면 1차원 배열을 반환한다
e.reshape(-1) #차원 수 : (12,)
>>>array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
e.reshape(1,-1).shape #차원 수 : (1,12)

0개의 댓글