numpyで配列を作成する#

import numpy as np

要素を直接指定して配列を作成する(np.array)#

a = np.array([[1, 2, 3], [4, 5, 6]])

# 関数化
def info(array):
    print('array: ', array)
    print('shape: ', array.shape)
    print('size: ', array.size)
    print('mean: ', array.mean())    
    print('sum: ', array.sum())
    
info(a)
array:  [[1 2 3]
 [4 5 6]]
shape:  (2, 3)
size:  6
mean:  3.5
sum:  21

要素がゼロの配列を作成する(np.zeros)#

a = np.zeros(4)
info(a)
array:  [0. 0. 0. 0.]
shape:  (4,)
size:  4
mean:  0.0
sum:  0.0

要素が1の配列を作成する(np.ones)#

a = np.ones(4)
info(a)
array:  [1. 1. 1. 1.]
shape:  (4,)
size:  4
mean:  1.0
sum:  4.0

要素が空の配列を作成する(np.empty)#

a = np.empty(shape=[4])
info(a)
array:  [1. 1. 1. 1.]
shape:  (4,)
size:  4
mean:  1.0
sum:  4.0

要素を一意の数値に指定して作成する(np.full)#

a = np.full([5, 4], 10)
info(a)
array:  [[10 10 10 10]
 [10 10 10 10]
 [10 10 10 10]
 [10 10 10 10]
 [10 10 10 10]]
shape:  (5, 4)
size:  20
mean:  10.0
sum:  200

順列要素として作成する(np.arange)#

a = np.arange(10)
info(a)
array:  [0 1 2 3 4 5 6 7 8 9]
shape:  (10,)
size:  10
mean:  4.5
sum:  45
# stopで指定した数字は入らないので注意
a = np.arange(start=10, stop=20, step=2)
info(a)
array:  [10 12 14 16 18]
shape:  (5,)
size:  5
mean:  14.0
sum:  70

順列を作成する(np.linspace)#

  • np.arangeとは異なり、配列の要素数を指定することができる

a = np.linspace(start=10, stop=20, num=2)
info(a)

指数ベースでの順列を作成する(np.logspace)#

  • 指数ベースでの配列作成(基数は10がデフォルト)

# 10^1から始まり、10^4で終わる配列を作成。要素数は4
a = np.logspace(start=1, stop=4, num=4)
info(a)
array:  [   10.   100.  1000. 10000.]
shape:  (4,)
size:  4
mean:  2777.5
sum:  11110.0

対数スケール(幾何級数)で等間隔に並んだ数字を返す(np.geomspace)#

a = np.geomspace(1, 1000, num=4)
info(a)
array:  [   1.   10.  100. 1000.]
shape:  (4,)
size:  4
mean:  277.75
sum:  1111.0

要素がrandomの配列を作成する(np.random)#

a = np.random.rand(3, 4)
info(a)
array:  [[0.7508038  0.65862125 0.26007837 0.8565904 ]
 [0.49285927 0.97450707 0.42321856 0.82244596]
 [0.43644984 0.17597482 0.00689489 0.28943564]]
shape:  (3, 4)
size:  12
mean:  0.5123233227838125
sum:  6.147879873405751