본문 바로가기

Programming/Python

[Python] Numpy 100 Exercises # 1 ~ 50

Overview

numpy 패키지를 잘 사용하기 위한 100개의 exercise를 기록한다.
아주 기초적인 내용부터 시작해서 주로 쓰이거나 꼭 필요한 것들 위주로 정리되어 있다.

Contents

# 1~10

1. Import the numpy package under the name np (★☆☆)

import numpy as np

 

 

2. Print the numpy version and the configuration (★☆☆)

print(np.__version__)
np.show_config()
더보기

1.17.4
blas_mkl_info:
  NOT AVAILABLE
blis_info:
  NOT AVAILABLE
openblas_info:
    library_dirs = ['C:\\projects\\numpy-wheels\\numpy\\build\\openblas']
    libraries = ['openblas']
    language = f77
    define_macros = [('HAVE_CBLAS', None)]
blas_opt_info:
    library_dirs = ['C:\\projects\\numpy-wheels\\numpy\\build\\openblas']
    libraries = ['openblas']
    language = f77
    define_macros = [('HAVE_CBLAS', None)]
lapack_mkl_info:
  NOT AVAILABLE
openblas_lapack_info:
    library_dirs = ['C:\\projects\\numpy-wheels\\numpy\\build\\openblas']
    libraries = ['openblas']
    language = f77
    define_macros = [('HAVE_CBLAS', None)]
lapack_opt_info:
    library_dirs = ['C:\\projects\\numpy-wheels\\numpy\\build\\openblas']
    libraries = ['openblas']
    language = f77
    define_macros = [('HAVE_CBLAS', None)]

 

 

3. Create a null vector of size 10 (★☆☆)

Z = np.zeros(10)
print(Z)
  • np.zeros() : 모든 원소가 0인 array 생성
더보기

[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]

 

 

4. How to find the memory size of any array (★☆☆)

Z = np.zeros((10,10))
print("%d bytes" % (Z.size * Z.itemsize))
  • memory size of array : (array size) x (itemsize) (bytes)
더보기

800 bytes

 

 

5. How to get the documentation of the numpy add function from the command line? (★☆☆)

$ python -c "import numpy; numpy.info(numpy.add)"
더보기

add(x1, x2[, out])

Add arguments element-wise.

Parameters
----------
x1, x2 : array_like
    The arrays to be added.  If ``x1.shape != x2.shape``, they must be
    broadcastable to a common shape (which may be the shape of one or
    the other).

Returns
-------
add : ndarray or scalar
    The sum of `x1` and `x2`, element-wise.  Returns a scalar if
    both  `x1` and `x2` are scalars.

Notes
-----
Equivalent to `x1` + `x2` in terms of array broadcasting.

Examples
--------
>>> np.add(1.0, 4.0)
5.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.add(x1, x2)
array([[  0.,   2.,   4.],
       [  3.,   5.,   7.],
       [  6.,   8.,  10.]])

 

 

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

Z = np.zeros(10)
Z[4] = 1
print(Z)
  • array[x] : array의 해당 원소에 접근
더보기

[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]

 

 

7. Create a vector with values ranging from 10 to 49 (★☆☆)

Z = np.arange(10,50)
print(Z)
  • np.arange(x,y) : x부터 y-1까지를 원소로 하는 array 생성
더보기

[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]

 

 

8. Reverse a vector (first element becomes last) (★☆☆)

Z = np.arange(50)
Z = Z[::-1]
print(Z)

 

더보기

[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  9  8  7  6  5  4  3  2  1  0]

 

 

9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)

Z = np.arange(9).reshape(3,3)
print(Z)
더보기

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

 

 

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

nz = np.nonzero([1,2,0,0,4,0])
print(nz)
더보기

(array([0, 1, 4], dtype=int64),)

 

 

# 11 ~ 20

11. Create a 3x3 identity matrix (★☆☆)

Z = np.eye(3)
print(Z)
  • np.eye() : 단위행렬 생성
더보기

[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

 

 

12. Create a 3x3x3 array with random values (★☆☆)

Z = np.random.random((3,3,3))
print(Z)
더보기

[[[0.69931062 0.55097081 0.32017653]
  [0.85589599 0.62537491 0.66547379]
  [0.63027559 0.55488013 0.81877111]]

 [[0.6751413  0.35247211 0.21324082]
  [0.74322659 0.76989407 0.50734443]
  [0.9159539  0.57626907 0.50309192]]

 [[0.45428572 0.17652545 0.92523143]
  [0.47568085 0.42734816 0.68421279]
  [0.72489703 0.13651959 0.04347421]]]

 

 

13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)

Z = np.random.random((10,10))
Zmin, Zmax = Z.min(), Z.max()
print(Zmin, Zmax)
더보기

0.0014380773502929989 0.9714747861015348

 

 

14. Create a random vector of size 30 and find the mean value (★☆☆)

Z = np.random.random(30)
m = Z.mean()
print(m)
더보기

0.46817182509609573

 

 

15. Create a 2d array with 1 on the border and 0 inside (★☆☆)

Z = np.ones((10,10))
Z[1:-1,1:-1] = 0
print(Z)
더보기

[[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]]

 

 

16. How to add a border (filled with 0's) around an existing array? (★☆☆)

Z = np.ones((5,5))
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
print(Z)
더보기

[[0. 0. 0. 0. 0. 0. 0.]
 [0. 1. 1. 1. 1. 1. 0.]
 [0. 1. 1. 1. 1. 1. 0.]
 [0. 1. 1. 1. 1. 1. 0.]
 [0. 1. 1. 1. 1. 1. 0.]
 [0. 1. 1. 1. 1. 1. 0.]
 [0. 0. 0. 0. 0. 0. 0.]]

 

 

17. What is the result of the following expression? (★☆☆)

print(0 * np.nan)
print(np.nan == np.nan)
print(np.inf > np.nan)
print(np.nan - np.nan)
print(np.nan in set([np.nan]))
print(0.3 == 3 * 0.1)
더보기

nan
False
False
nan
True
False

 

 

18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)

Z = np.diag(1 + np.arange(4), k=-1)
print(Z)
  • np.diag() : 대각행렬 생성
  • np.eye() : 단위행렬 생성
더보기

[[0 0 0 0 0]
 [1 0 0 0 0]
 [0 2 0 0 0]
 [0 0 3 0 0]
 [0 0 0 4 0]]

 

 

19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)

Z = np.zeros((8, 8), dtype=int)
Z[1::2, ::2] = 1
Z[::2, 1::2] = 1
print(Z)
더보기

[[0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]]

 

 

20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element?

print(np.unravel_index(99, (6, 7, 8)))
더보기

(1, 5, 3)

 

 

# 21 ~ 30

21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)

Z = np.tile(np.array([[0, 1], [1, 0]]), (4, 4))
print(Z)
더보기

[[0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]]

 

 

22. Normalize a 5x5 random matrix (★☆☆)

Z = np.random.random((5, 5))
Z = (Z - np.mean(Z)) / (np.std(Z))
print(Z)
더보기

[[-1.34202211  1.41093131  0.24227598 -1.37216485 -1.03614721]
 [-0.49915606  0.16836807 -1.50455627 -0.93955895 -0.58850416]
 [-0.99646982  1.48771656  1.35516983 -0.86813016 -0.47899371]
 [ 0.71994457  1.34594215  1.12614372 -0.62265598 -0.37799986]
 [ 0.12316456  1.50425513  1.08914065 -0.60687791  0.66018453]]

 

 

23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)

color = np.dtype([("r", np.ubyte, 1),
                  ("g", np.ubyte, 1),
                  ("b", np.ubyte, 1),
                  ("a", np.ubyte, 1)])
                  
print(color)
더보기

[('r', 'u1'), ('g', 'u1'), ('b', 'u1'), ('a', 'u1')]

 

 

24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)

Z = np.dot(np.ones((5, 3)), np.ones((3, 2)))
print(Z)

# Alternative solution, in Python 3.5 and above
Z = np.ones((5, 3)) @ np.ones((3, 2))
print(Z)
더보기

[[3. 3.]
 [3. 3.]
 [3. 3.]
 [3. 3.]
 [3. 3.]]
[[3. 3.]
 [3. 3.]
 [3. 3.]
 [3. 3.]
 [3. 3.]]

 

 

25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)

Z = np.arange(11)
Z[(3 < Z) & (Z <= 8)] *= -1
print(Z)
더보기

[ 0  1  2  3 -4 -5 -6 -7 -8  9 10]

 

 

26. What is the output of the following script? (★☆☆)

print(sum(range(5), -1))
from numpy import *
print(sum(range(5), -1))

 

 

27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)

# Z = np.arange(9).reshape(3,3)

Z ** Z
2 << Z >> 2
Z < - Z
1j * Z
Z / 1 / 1
Z < Z > Z
  • X ** X : X 의 X 제곱
  • (2 << X) or (X >> 2) : 2의 X 제곱
더보기

print(Z) :

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

print(Z**Z) :

[[       1        1        4]
 [      27      256     3125]
 [   46656   823543 16777216]]

print(2 << Z >> 2) :

[[  0   1   2]
 [  4   8  16]
 [ 32  64 128]]

print(Z < -Z) :

[[False False False]
 [False False False]
 [False False False]]

print(1j * Z) :

[[0.+0.j 0.+1.j 0.+2.j]
 [0.+3.j 0.+4.j 0.+5.j]
 [0.+6.j 0.+7.j 0.+8.j]]

print(Z / 1 / 1) :

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

print(Z < Z > Z) :

ValueError: The truth value of an array with more than one element is ambiguous.

 

 

 

28. What are the result of the following expressions?

print(np.array(0) / np.array(0))
print(np.array(0) // np.array(0))
print(np.array([np.nan]).astype(int).astype(float))
더보기

print(np.array(0) / np.array(0)) :

RuntimeWarning: invalid value encountered in true_divide

print(np.array(0) // np.array(0)) :

RuntimeWarning: divide by zero encountered in floor_divide

print(np.array([np.nan]).astype(int).astype(float)) :

nan
0
[-2.14748365e+09]

 

 

29. How to round away from zero a float array ? (★☆☆)

Z = np.random.uniform(-10, +10, 10)
print(Z)
print(np.copysign(np.ceil(np.abs(Z)), Z))
  • np.random.uniform() : 균등분포에서 무작위 추출
  • np.abs() : 절댓값
  • np.ceil() : 올림
  • np.copysign(x, y) : -부호 복사(x의 부호를 y 부호와 같게 만들어준다.)
더보기

[-0.70145049 -7.62246672  9.65644631 -0.2582516  -0.77413856  3.20554648
 -8.329206    3.33455073  2.14876206 -8.69329696]


[-1. -8. 10. -1. -1.  4. -9.  4.  3. -9.]

 

 

30. How to find common values between two arrays? (★☆☆)

Z1 = np.random.randint(0, 10, 10)
Z2 = np.random.randint(0, 10, 10)
print(Z1)
print(Z2)
print(np.intersect1d(Z1, Z2))
  • np.random.randint(low, high, size) : 범위 내 무작위 정수 추출
  • np.intersect1d() : 공통 원소 추출
더보기

[1 0 5 0 9 0 8 9 6 6]
[9 4 7 1 4 5 9 9 7 6]
[1 5 6 9]

 

 

 

 

References

1. https://github.com/rougier/numpy-100