Untitled2

numpy.reshape(a, newshape, order='C)

In [2]:
import numpy as np

reshape: 원하는 shape으로 바꿔줌

In [6]:
a = np.arange(10)
b = np.reshape(a, (2, 5))
c = a.reshape((2, 5))

print('a:\n', a)
print('b:\n', b)
print('c:\n', c)
a:
 [0 1 2 3 4 5 6 7 8 9]
b:
 [[0 1 2 3 4]
 [5 6 7 8 9]]
c:
 [[0 1 2 3 4]
 [5 6 7 8 9]]

하나를 지정하지 않고 -1을 쓰면 자동으로 shape이 됨

계산이 귀찮거나 row나 column 강조하고싶을 때 사용해도 좋음

In [11]:
a = np.arange(10)

b = a.reshape((2, -1)) # row가 강조되는 느낌 
c = a.reshape((5, -1))

print(b.shape)
print(c.shape)
(2, 5)
(5, 2)

numpy.resize(a, new_shape)

원소의 개수를 바꿔줄 때 유용

아래의 코드는 reshape과 결과가 같음

In [12]:
a = np.arange(10)

b = np.resize(a, (2, 5))

print('a:\n', a)
print('b:\n', b)
a:
 [0 1 2 3 4 5 6 7 8 9]
b:
 [[0 1 2 3 4]
 [5 6 7 8 9]]

but reshape은 원소의 개수가 다르면 오류가 나지만 resize는 자동으로 맞춰줌

In [14]:
a = np.arange(5)

b = np.reshape(a, (10,))
print('b:\n', b)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-fcc2b57f1b7d> in <module>
      1 a = np.arange(5)
      2 
----> 3 b = np.reshape(a, (10,))
      4 print('b:\n', b)

<__array_function__ internals> in reshape(*args, **kwargs)

~\anaconda3\lib\site-packages\numpy\core\fromnumeric.py in reshape(a, newshape, order)
    299            [5, 6]])
    300     """
--> 301     return _wrapfunc(a, 'reshape', newshape, order=order)
    302 
    303 

~\anaconda3\lib\site-packages\numpy\core\fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
     59 
     60     try:
---> 61         return bound(*args, **kwds)
     62     except TypeError:
     63         # A TypeError occurs if the object does have such a method in its

ValueError: cannot reshape array of size 5 into shape (10,)
In [16]:
a = np.arange(5)

b = np.resize(a, (10,))
print('b:\n', b)
# 앞에서부터 반복해서 만듦 
b:
 [0 1 2 3 4 0 1 2 3 4]

size가 늘어나도 오류가 안나므로 조심해야 함

 
 

resize는 in-place (return값이 없고 바로 바뀜)

In [18]:
a = np.arange(4)

b = a.resize((2, 2))

print('a: \n', a)
print('b:\n', b)
a: 
 [[0 1]
 [2 3]]
b:
 None

그래서 아래와 같이 사용하는게 좋음

In [21]:
a = np.arange(5)

a.resize((2,2))
print(a)
[[0 1]
 [2 3]]

reshape은 오류남

In [24]:
a = np.arange(5)

a.reshape((2,2))
print(a)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-24-f82f97014a0d> in <module>
      1 a = np.arange(5)
      2 
----> 3 a.reshape((2,2))
      4 print(a)

ValueError: cannot reshape array of size 5 into shape (2,2)

+ Recent posts