Python_Numpy02
In [1]:
import numpy as np
In [2]:
import numpy as np 
A= np.arange(0,15,2)
print(A)
[ 0  2  4  6  8 10 12 14]
In [6]:
print(A.shape)
for i in range(A.size):
    print("A[{}] : {}".format(i,A[i]))
(8,)
A[0] : 0
A[1] : 2
A[2] : 4
A[3] : 6
A[4] : 8
A[5] : 10
A[6] : 12
A[7] : 14
In [8]:
# -1부터 -8까지 나오도록 출력 
print(A.shape)
for i in range(A.size):
    print("A[{}] : {}".format(-(i+1),A[-(i+1)]))
(8,)
A[-1] : 14
A[-2] : 12
A[-3] : 10
A[-4] : 8
A[-5] : 6
A[-6] : 4
A[-7] : 2
A[-8] : 0
In [21]:
import numpy as  np

A= np.arange(12).reshape(3,4)
print(A)
print("A.ndim:",A.ndim)
print(A.shape, A.shape[0], A.shape[1])

for i in range(A.shape[0]):
    for j in range(A.shape[1]):
        print("A[{0}][{1}] : {2} ".format(i,j,A[i][j]), end=" ")
    print()
    
print()
for i in range(A.shape[0]):
    print("A[{0}][{1}] : {2:2d}". format(i,j,A[i][j]), end=" ")
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
A.ndim: 2
(3, 4) 3 4
A[0][0] : 0  A[0][1] : 1  A[0][2] : 2  A[0][3] : 3  
A[1][0] : 4  A[1][1] : 5  A[1][2] : 6  A[1][3] : 7  
A[2][0] : 8  A[2][1] : 9  A[2][2] : 10  A[2][3] : 11  

A[0][3] :  3 A[1][3] :  7 A[2][3] : 11
In [106]:
import numpy as  np

A= np.arange(9).reshape(3,3)
print(A)
print()
for row in A: #A => [[0.1,2], [3,4,5], [6,7,8]]
    print(row)
print()
print(A.T) #전치행렬: 행과 열의 값을 바꿈 
print()
for column in A.T:
    print(column)
[[0 1 2]
 [3 4 5]
 [6 7 8]]

[0 1 2]
[3 4 5]
[6 7 8]

[[0 3 6]
 [1 4 7]
 [2 5 8]]

[0 3 6]
[1 4 7]
[2 5 8]

flat

In [26]:
import numpy as  np
A=np.arange(9).reshape(3,3)
print(A)
print()
for a in A.flat: #개별 원소로 바뀜
    print(a, end=" ")
[[0 1 2]
 [3 4 5]
 [6 7 8]]

0 1 2 3 4 5 6 7 8
In [108]:
import numpy as  np
A= np.arange(0,20,2) #1차원 배열 생성 
print(A)
[ 0  2  4  6  8 10 12 14 16 18]
In [38]:
print(A[:]) #전체원소 
print(A[0:3])
print(A[:3]) # 0에서 시작하면 생략하능
[ 0  2  4  6  8 10 12 14 16 18]
[0 2 4]
[0 2 4]
In [37]:
print(A[7:10])
print(A[7:]) # 끝 인덱스 생략가능 
[14 16 18]
[14 16 18]
In [110]:
print(A[::2]) #첫번째 원소부터 2씩 건너뜀
[ 0  4  8 12 16]
In [48]:
print(A[:-2]) #마지막 2개 원소 제외 
print(A[-10:-2])

print(A[-2:]) #마지막 원소 2개만 취함
[ 0  2  4  6  8 10 12 14]
[ 0  2  4  6  8 10 12 14]
[16 18]
In [43]:
print(A[0:3].shape)
print(A[0:3].ndim)
(3,)
1
In [49]:
print(A)
A[0:3]=100
print(A)
[ 0  2  4  6  8 10 12 14 16 18]
[100 100 100   6   8  10  12  14  16  18]
In [102]:
import numpy as  np
A=np.arange(1,13).reshape(3,4)
print(A)
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]

 
 

각 원소에 접근

A[row][col] or A[row,col]

In [104]:
for i in range(A.shape[0]):
    for j in range(A.shape[1]):
        print("A[{0}][{1}] : {2:2d} or A[{3}, {4}] : {5:2d}".format(i, j, A[i][j], i, j, A[i, j]))
A[0][0] :  1 or A[0, 0] :  1
A[0][1] :  2 or A[0, 1] :  2
A[0][2] :  3 or A[0, 2] :  3
A[0][3] :  4 or A[0, 3] :  4
A[1][0] :  5 or A[1, 0] :  5
A[1][1] :  6 or A[1, 1] :  6
A[1][2] :  7 or A[1, 2] :  7
A[1][3] :  8 or A[1, 3] :  8
A[2][0] :  9 or A[2, 0] :  9
A[2][1] : 10 or A[2, 1] : 10
A[2][2] : 11 or A[2, 2] : 11
A[2][3] : 12 or A[2, 3] : 12
In [55]:
for i in range(A.shape[0]):
     print("A[{0}] : {1} or A[{2},:] : {3}".format(i,A[i],i,A[i,:]))
A[0] : [1 2 3 4] or A[0,:] : [1 2 3 4]
A[1] : [5 6 7 8] or A[1,:] : [5 6 7 8]
A[2] : [ 9 10 11 12] or A[2,:] : [ 9 10 11 12]
In [56]:
print(A)
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
In [57]:
print(A[:2,:2])
[[1 2]
 [5 6]]
In [58]:
A[:2,:2]=0
print(A)
[[ 0  0  3  4]
 [ 0  0  7  8]
 [ 9 10 11 12]]
In [111]:
import numpy as  np
A=np.arange(1,13).reshape(3,4)
print(A)
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
In [112]:
print(A[0])
print(A[:,1])
print(A[...,1])
[1 2 3 4]
[ 2  6 10]
[ 2  6 10]
In [65]:
import numpy as  np
A=np.array([2,4,6,8]).reshape(2,2)
B=np.array([2,2,2,2]).reshape(2,2)
print(A)
print(B)
[[2 4]
 [6 8]]
[[2 2]
 [2 2]]
In [67]:
print(A+B)
print()
print(A-B)
print()
print(A*B)
print()
print(A/B)
[[ 4  6]
 [ 8 10]]

[[0 2]
 [4 6]]

[[ 4  8]
 [12 16]]

[[1. 2.]
 [3. 4.]]
In [68]:
print(A@B) 
[[12 12]
 [28 28]]
In [69]:
print(np.dot(A,B))
print(A.dot(B))
[[12 12]
 [28 28]]
[[12 12]
 [28 28]]

다른 크기의 배열간의 산술연산(브로드캐스팅)

A.shape= (2,3,4,5)
B.shape= (5,) => B의 차원의 개수가 같아지도록 B shape 왼쪽에 1추가
B.shape= (1,1,1,5)

  • 두 배열을 비교
  • 대응하는 차원이 같거나 한쪽이 1인 경우에만 브로드캐스팅 가능
    참고) 행렬 곱셈 규칙 : 행렬(m x n) x 행렬(n x a) -> (m xa) 행렬
    브로드캐스팅해서 행렬곱셈은 적용안됨..

1Q
A.shape : (2,1,3,1)
B.shape : (6,1,3)

=> 브로드캐스팅이 가능한가?

1A)
B의 차원의 개수가 같아지도록 함
A.shape : (2,1,3,1)
B.shape : (6,1,3)
B.shape : (1,6,1,3)

-> 가능하다.

2Q)
A.shape : (2,3,4)
B.shape : (3,1)

=> 브로드캐스팅이 가능한가?

2A)
A.shape : (2,3,4)
B.shape : (3,1)
B.shape : (1,3,1)

-> 가능하다

3Q)
A.shape : (3,)
B.shape : (4,)
=> 브로드캐스팅이 가능한가?

3A)
A.shape : (3,)
B.shape : (4,)
-> 브로드캐스팅 불가능

4Q)
A.shape : (3,3,5)
B.shape : ()
=> 브로드캐스팅이 가능한가?

4A)
A.shape : (3,3,5)
B.shape : (1,1,1)

-> 브로드캐스팅 가능

+
A.shape: (3,4)
B.shape: (3,) => (1,3)

-> 브로드캐스팅 NO

In [125]:
import numpy as  np
A=np.arange(10,130,10).reshape(3,4)
print(A)
print(A.shape)
print()
B=np.arange(1,5)
print(B)
print(B.shape)
[[ 10  20  30  40]
 [ 50  60  70  80]
 [ 90 100 110 120]]
(3, 4)

[1 2 3 4]
(4,)
In [126]:
A+B
Out[126]:
array([[ 11,  22,  33,  44],
       [ 51,  62,  73,  84],
       [ 91, 102, 113, 124]])
In [138]:
import numpy as  np
A=np.arange(10,130,10).reshape(3,4)
print(A)
print(A.shape)
print()
B=np.arange(1,4)
print(B)
print(B.shape)
[[ 10  20  30  40]
 [ 50  60  70  80]
 [ 90 100 110 120]]
(3, 4)

[1 2 3]
(3,)
In [139]:
A+B #브로드캐스팅 no
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-139-c8aa45903e18> in <module>
----> 1 A+B #브로드캐스팅 no

ValueError: operands could not be broadcast together with shapes (3,4) (3,) 
In [133]:
import numpy as  np
A= np.arange(10,130,10).reshape(3,4)
print(A)
print()
B=5
A+B
[[ 10  20  30  40]
 [ 50  60  70  80]
 [ 90 100 110 120]]

Out[133]:
array([[ 15,  25,  35,  45],
       [ 55,  65,  75,  85],
       [ 95, 105, 115, 125]])
In [129]:
A*B
Out[129]:
array([[ 50, 100, 150, 200],
       [250, 300, 350, 400],
       [450, 500, 550, 600]])
In [134]:
import numpy as np
A = np.arange(10,130,10).reshape(3,4)
print(A)
print(A.shape)
B = np.arange(1,5)
print(B)
print(B.shape)
[[ 10  20  30  40]
 [ 50  60  70  80]
 [ 90 100 110 120]]
(3, 4)
[1 2 3 4]
(4,)
In [136]:
A*B
Out[136]:
array([[ 10,  40,  90, 160],
       [ 50, 120, 210, 320],
       [ 90, 200, 330, 480]])
In [135]:
A@B
Out[135]:
array([ 300,  700, 1100])
In [164]:
B= np.array([1, 2, 3])
print(B.shape)
(3,)
In [165]:
A= np.array([[1], [2], [3]])
print(A.shape)
(3, 1)
In [174]:
C= np.array([[[1, 2, 3, 4], [4, 5, 6,7],[1, 2, 3, 4]], [[1, 2, 3, 4],[1, 2, 3, 4], [4, 5, 6,7]], ])
print(C.shape)
(2, 3, 4)
In [179]:
A*C
Out[179]:
array([[[ 1,  2,  3,  4],
        [ 8, 10, 12, 14],
        [ 3,  6,  9, 12]],

       [[ 1,  2,  3,  4],
        [ 2,  4,  6,  8],
        [12, 15, 18, 21]]])
In [181]:
B*C
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-181-03507f8da0a7> in <module>
----> 1 B*C

ValueError: operands could not be broadcast together with shapes (3,) (2,3,4) 
In [182]:
C*B
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-182-a5fce2007bf4> in <module>
----> 1 C*B

ValueError: operands could not be broadcast together with shapes (2,3,4) (3,) 
In [183]:
C*A
Out[183]:
array([[[ 10,  40,  90, 160],
        [200, 300, 420, 560],
        [ 90, 200, 330, 480]],

       [[ 10,  40,  90, 160],
        [ 50, 120, 210, 320],
        [360, 500, 660, 840]]])

+ Recent posts