100 numpy exercises(1 – 10)

numpyの理解を深めるために100問エクササイズに挑戦してみました。

今回は最初の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.19.5
blas_mkl_info:
  NOT AVAILABLE
blis_info:
  NOT AVAILABLE
openblas_info:
    libraries = ['openblas', 'openblas']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None)]
blas_opt_info:
    libraries = ['openblas', 'openblas']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None)]
lapack_mkl_info:
  NOT AVAILABLE
openblas_lapack_info:
    libraries = ['openblas', 'openblas']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None)]
lapack_opt_info:
    libraries = ['openblas', 'openblas']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None)]

3. Create a null vector of size 10.

Z = np.zeros(10)
print(Z)
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]

メソッド「zeros」はゼロ埋めの配列を作ってくれます。

4. How to find the memory size of any array.

Z = np.zeros((10,10))
print("%d bytes" % (Z.size * Z.itemsize))
800 bytes

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

Z[::-1]は配列の反転です。

9. Create a 3×3 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]]
  1. 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]),)

メソッド「nonzero」は非ゼロでない要素のインデックスを返してくれます。

次回は11〜20問目に挑戦してみます。