🐍Python/Numpy

[Numpy] Numpy 연습문제 1~10

728x90
반응형

1. Import the numpy package under the name

-> import numpy as np

2. Print the numpy version and the configuration 

-> print(np.__version__)

3. Create a null vector of size 10

-> z= np.zeros(10)
    print(z)

A : [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]

해설 : np.zeros를 통해 N개의 0으로 채워진 array를 구성할 수 있다. 

4. How to find the memory size of any array

-> z = np.zeros((10,10))
    print("%d bytes" % (z.size* z.itemsize))

A : 800 bytes

해설 : bytes = size * itemize

5. How to get the documentation of the numpy add function from the command line? 

-> %run `python -c "import numpy; numpy.info(numpy.add)”`

6. Create a null vector of size 10 but the fifth value which is 1

->  Z = np.zeros(10)
     Z[4] = 1
     print(Z)

A : [0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]

해설 : null vector을 만들고 array가 0부터 시작이기 때문에 [4]로 5번째 vector 1로 변경

7. Create a vector with values ranging from 10 to 49

-> Z = np.arange(10,50)
    print(Z)

A : [10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49]

해설 : np.arrange(A,B)를 하면 A ~ (B-1)까지 출력이 된다.

8. Reverse a vector (first element becomes last) 

-> Z[::-1]

A : array([49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33,
       32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16,
       15, 14, 13, 12, 11, 10])

해설 : [::-1]을 통해 전체 array를 간격 1을 유지하며 거꾸로 출력한다 [::-2]일 경우 2의 간격을 갖고 거꾸로 출력된다. 그냥 [::N]일 경우 기존 순서대로 N의 간격을 갖고 출력된다.

9. Create a 3x3 matrix with values ranging from 0 to 8

-> Z = np.arange(0,9)
    Z.reshape(3,3)

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

해설 : np.arrange를 통해 0~9 Vector를 생성하고, reshape을 통해 (3,3)형태로 변환해준다.

10. Find indices of non-zero elements from [1,2,0,0,4,0]

-> Z = [1,2,0,0,4,0]
    np.nonzero(Z)

A : (array([0, 1, 4]),)

해설 : np.nonzero를 통해 array에서 0이 아닌 vector들의 위치를 나타낸다. 0,1,4번째가 Nonzero라고 도출됐다.




728x90
반응형