PythonのNumpy Ndarrayを作成する
Table of Contents
リファレンス
詳細はnumpy公式APIリファレンスを参照してください。
準備
pip install -U pip
pip install numpy
作成方法
n次元配列(ndarray)はnumpyで最も重要で基本的なクラスです。コンストラクタを持っていますが、要素は初期化されません。
# Interactive mode
python
>>> import numpy as np
>>> np.ndarray(3)
array([0.e+000, 5.e-324, 1.e-323]) # random values
# An array of 3x2
>>> np.ndarray((3, 2))
array([[0.0e+000, 4.9e-324],
[9.9e-324, 1.5e-323],
[2.0e-323, 2.5e-323]]) # random values
arrayはndarrayオブジェクトを作成する便利なインターフェースです。配列オブジェクトを受け取り、それによって要素が初期化されます。
# Interactive mode
python
>>> import numpy as np
# Create an array
>>> np.array([0, 1, 2])
array([0, 1, 2])
# An array of 2x3
>>> np.array([[0, 1, 2], [3, 4, 5]])
array([[0, 1, 2],
[3, 4, 5]])
# Type provided
>>> np.array([0, 1, 2], dtype=float)
array([0., 1., 2.])
zeros:
# Interactive mode
python
>>> import numpy as np
# Create an array of zeros
# Default dtype is numpy.float64
>>> np.zeros(2)
array([0., 0.])
# Type provided
>>> np.zeros((2, 3), dtype=int)
array([[0, 0, 0],
[0, 0, 0]])
ones:
# Create an array of zeros
# Default dtype is numpy.float64
>>> np.ones(2)
array([1., 1.])
# Type provided
>>> np.ones((2, 3), dtype=np.int8)
array([[1, 1, 1],
[1, 1, 1]], dtype=int8)
full:
# Create an array filled with given value
>>> np.full(2, 100)
array([100, 100])
>>> np.full((2, 3), np.inf)
array([[inf, inf, inf],
[inf, inf, inf]])
>>> np.full((2, 3), [0, 1, 2])
array([[0, 1, 2],
[0, 1, 2]])
array_likeインターフェース(zeros_like、ones_like、full_like)は、与えられた配列と同じ形状と型の配列を作成します。
zeros_like:
# Interactive mode
python
>>> import numpy as np
>>> a = np.array([0, 1, 2], dtype=np.float64)
>>> a
array([0., 1., 2.])
>>> a.dtype
dtype('float64')
>>> np.zeros_like(a)
array([0., 0., 0.])
>>> np.zeros_like(a).dtype
dtype('float64')
ones_like:
>>> np.ones_like(a)
array([1., 1., 1.])
>>> np.ones_like(a).dtype
dtype('float64')
full_like:
>>> np.full_like(a, 100)
array([100., 100., 100.])
>>> np.full_like(a, 100).dtype
dtype('float64')