Python

[Numpy] 기초 및 함수 정리-2

zzheng 2024. 6. 10. 19:28

Numpy 배열관련 주요 함수

  • shape: 배열의 형태 반환
  • reshape: 배열의 형태 변환
  • ndim: 배열의 차원 반환
  • len
  • type
  • T: 행, 열 전환
  • Slicing: 특정 열이나 행을 선택하여 추출
  • np.ones, np.ones_like, np.zeros, np.zeros_like
  • np.arange
  • np.newaxis: 차원 확장
  • np.vstack: 수직으로 쌓음
  • np.hstack: 수평적으로 병합

 

벡터화 계산(**)

  • 원소 하나 하나씩 계산하는 것이 아니라 배열 단위로 계산
  • 브로드캐스팅(broadcasting): 행렬끼리 연산할 때 크기가 다른 경우 이를 알아서 확대 해주는 기능
  • Filtering
a = np.array([1,2,3])
b = np.array([4,5,6])
c = a+b+b
c

#결과
array([ 9, 12, 15])
c = np.array([7,5,9,10,4,10,6,2]).reshape(2,4)
c
d = np.array([1,3,4,9, 14,7,6,4]).reshape(2,4)
d

c - d

#결과
array([[ 7,  5,  9, 10],
       [ 4, 10,  6,  2]])
       
array([[ 1,  3,  4,  9],
       [14,  7,  6,  4]])

array([[  6,   2,   5,   1],
       [-10,   3,   0,  -2]])

 

배열 생성(추가) & random 배열 생성

np.random.random((2,3))

#결과
array([[0.09376935, 0.84858674, 0.09043722],
       [0.37073364, 0.96106484, 0.20899047]])
np.random.randint(1, 10, size=(3,3,2))

#결과
array([[[6, 5],
        [2, 9],
        [1, 6]],

       [[5, 6],
        [6, 4],
        [3, 9]],

       [[9, 5],
        [9, 5],
        [5, 3]]])
np.random.randn( 2,3,4)

#결과
array([[[ 0.68274235, -0.57846001, -0.3871027 , -0.50101724],
        [-0.43481998, -0.37410914,  2.36478688,  0.49867887],
        [ 0.76235902, -1.97600708,  0.62716257, -0.00792765]],

       [[ 0.912556  , -1.88721443, -0.34173504,  0.19996167],
        [ 0.06519137,  0.54852346,  0.97491204, -0.41423114],
        [-4.00812346,  1.21815569, -0.95270882,  0.38813928]]])
B = np.arange(1,10)
B

#결과
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
C = B.astype(np.float16)
C

#결과
array([1., 2., 3., 4., 5., 6., 7., 8., 9.], dtype=float16)
D  = np.array([1,0,1,0,1,0])
D.astype(bool)

#결과
array([ True, False,  True, False,  True, False])
np.array([ True, False,  True, False,  True, False]).astype(int)

#결과
array([1, 0, 1, 0, 1, 0])
np.random.sample( (2,3,4))

#결과
array([[[0.10311474, 0.68310975, 0.09029382, 0.43225269],
        [0.84511565, 0.78895826, 0.2482628 , 0.90676911],
        [0.2544932 , 0.01302354, 0.35666697, 0.69806558]],

       [[0.79591878, 0.2666043 , 0.46944787, 0.60326116],
        [0.29791698, 0.90610626, 0.99926274, 0.19477641],
        [0.83556007, 0.26022634, 0.36512627, 0.20099094]]])