take a look at the Python tutorial.
conda install numpy
NumPy’s main object is the homogeneous multidimensional array(NumPyのメインオブジェクトは、多次元(均質な(同じ型の))配列になる).
It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. ( NumPyのオブジェクトは、すべて同じ型で、 正の整数のタプルで添字付けされた(たいてい数字)の要素のみのテーブル。)
In Numpy dimensions(次元) are called axes(軸). The number of axes(軸の数) is rank(ランク).
For example, the coordinates of a point in 3D space [1, 2, 1]
is an array of rank 1, because it has one axis.([1,2,1])
That axis has a length of 3. (その1軸は長さ3をもつ)
In example pictured below, the array has rank 2 (it is 2-dimensional).
The first dimension (axis) has a length of 2,([1.,...],[0.,...])
the second dimension has a length of 3.([1.,0.,0.])
[[ 1., 0., 0.],
[ 0., 1., 2.]]
Numpy’s array class is called ndarray.
It is also known by the alias array. Note that numpy.array is not the same as the Standard Python Library class array.array, (標準Pythonライブラリのarray.arrayクラスとは別物。)
import numpy as np
a = np.arange(15).reshape(3, 5)
a
array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]])
the number of axes (dimensions) of the array. 配列の軸(次元)数。
In the Python world, the number of dimensions is referred to as rank.
a.ndim
2
the dimensions of the array. 配列の寸法。
This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m). (これは各次元の配列のサイズを表す整数のタプル。 n行m列の行列の場合、shapeは (n,m) となる。)
The length of the shape tuple is therefore the rank, or number of dimensions, ndim.(shapeタプルの長さはランク、または次元数 ndim になる)
a.shape
(3, 5)
the total number of elements of the array. (配列の要素のトータル数。)
This is equal to the product of the elements of shape.
a.size
15
an object describing the type of the elements in the array. (配列中の要素のtype(型)を記述するオブジェクト)
One can create or specify dtype’s using standard Python types. (標準のPythonのtype(bool, int, float, complex)を用いて作成もしくは指定することができ、
Additionally NumPy provides types of its own.
NumPy も、独自のtypeを提供している。)
numpy.int32
, numpy.int16
, and numpy.float64
are some examples.
a.dtype
dtype('int32')
文字列型については,ビルトイン型の str とは,少し違う。
numpy.ndarray
では、要素の大きさが同じである必要があるため、
文字列は固定長になる。
Python の文字列型に対応する NumPy での文字列型は,NumPy の型を返す関数 np.dtype()
を用いて, np.dtype('S<文字列長>') [4]
のように指定する。
例えば,最大長が16である文字列を扱う場合は np.dtype("S16")
のように指定する。
Unicode文字列の場合は,この S
を U
に置き換えます.
the size in bytes of each element of the array. (配列の各要素のバイト数。)
For example, an array of elements of type float64 has itemsize 8 (=64/8), while one of type complex32 has itemsize 4 (=32/8).
It is equivalent to ndarray.dtype.itemsize
.
a.itemsize
4
a.dtype.itemsize
4
the buffer containing the actual elements of the array. (配列の実際の要素を収容しているバッファ。)
Normally, we won’t need to use this attribute because we will access the elements in an array using indexing facilities. (配列の要素には添字機能を用いてアクセスできるので、普通はこの属性を用いる必要はないだろう。)
a.data
<memory at 0x000001737C7B51F8>
type(a)
numpy.ndarray
b = np.array([6, 7, 8])
b
array([6, 7, 8])
type(b)
numpy.ndarray
c = np.array((9, 10, 11))
c
array([ 9, 10, 11])
type(c)
numpy.ndarray
There are several ways to create arrays. (配列を作成する方法は何通りかある。)
For example, you can create an array from a regular Python list or tuple using the array function. 普通のPythonのリストやタプルからarray関数で作成する方法。
The type of the resulting array is deduced from the type of the elements in the sequences. (出来上がる配列のtypeは、シーケンスの要素のtype から推論される。)
np.array()
関数による生成¶numpy.array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0)
Create an array.
最初の引数 object
には,配列の内容を,array_like
というtype で与える。
この array_like
というtype は,配列を np.ndarray
の他,(多重)リストや(多重)タプルで表現したもの。
もう一つの引数 dtype は,配列の要素の型を指定しする。
要素が 1, 2, 3 である長さ 3 のベクトルの例:
import numpy as np
a = np.array([1, 2, 3])
a
array([1, 2, 3])
タプルを使った表現も可能:
a = np.array((10, 20, 30))
a
array([10, 20, 30])
リストの要素に numpy.ndarray
やタプルを含むことも可能:
a = np.array([1.0, 2.0, 3.0])
b = np.array([a, (10, 20, 30)])
b
array([[ 1., 2., 3.], [ 10., 20., 30.]])
import numpy as np
a = np.array([2,3,4])
a
array([2, 3, 4])
a.dtype
dtype('int32')
b = np.array([1.2, 3.5, 5.1])
b
array([ 1.2, 3.5, 5.1])
b.dtype
dtype('float64')
A frequent error consists in calling array with multiple numeric arguments, rather than providing a single list of numbers as an argument. (array関数の引数に数値のリストを渡すところを複数の数値をそのまま引数に渡して、エラーになるというのはよくある。)
a = np.array(1,2,3,4) # error
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-21-979c362d66e0> in <module>() ----> 1 a = np.array(1,2,3,4) # error ValueError: only 2 non-keyword arguments accepted
a = np.array([1,2,3,4]) # Right
array transforms sequences of sequences into two-dimensional arrays, sequences of sequences of sequences into three-dimensional arrays, and so on. (array は、シークエンスのシークエンスを2次元配列へ、 シークエンスのシークエンスのシークエンスを3次元配列へ、といったような変換をしてくれる。)
b = np.array([(1.5, 2, 3), (4, 5, 6)])
b
array([[ 1.5, 2. , 3. ], [ 4. , 5. , 6. ]])
c = np.array([
[[1, 2, 3],
[4, 5, 6]],
[[7, 8, 9],
[10, 11, 12]]
])
c
array([[[ 1, 2, 3], [ 4, 5, 6]], [[ 7, 8, 9], [10, 11, 12]]])
c.shape
(2, 2, 3)
The type of the array can also be explicitly specified at creation time(配列作成時に、typeを明示的に指定することも可能):
c = np.array([
[1 + 1j, 2],
[3, 4]
], dtype=complex)
c
array([[ 1.+1.j, 2.+0.j], [ 3.+0.j, 4.+0.j]])
Often, the elements of an array are originally unknown, but its size is known. (配列の要素が最初は不明だが、サイズはわかっているということもある。)
Hence, NumPy offers several functions to create arrays with initial placeholder content. (そのために、NumPy は、初めはplaceholder の内容を入れて配列を作成する関数をいくつか用意している。)
These minimize the necessity of growing arrays, an expensive operation. 配列を拡大する(これはコストのかかる操作)必要性を最小限にしてくれる。
配列の dtype
属性を指定するには,
numpy.array()
などの配列生成関数の dtype
引数で指定する方法と,numpy.ndarray
の numpy.ndarray.astype()
メソッドを使う方法とがある.dtype
引数を指定する方法:
np.array()
では、要素が全て整数の場合は、要素の型は整数になるが、
それを浮動小数点にするには、次のように指定する:
a = np.array([1, 2, 3])
a.dtype
dtype('int32')
a = np.array([1, 2, 3], dtype=np.float)
a.dtype
dtype('float64')
浮動小数点型の配列を複素数型で作り直す場合は,次のようになる:
a = np.array([1.0, 1.5, 2.0])
a.dtype
dtype('float64')
a = np.array(a, dtype=np.complex)
a.dtype
dtype('complex128')
a
array([ 1.0+0.j, 1.5+0.j, 2.0+0.j])
numpy.ndarray.astype()
メソッドを使う方法:
メソッドを使う方針でも,メソッド np.ndarray.astype()
が同様に利用できる。
a = np.array([1, 2, 3])
a.dtype
dtype('int32')
a = a.astype(np.float)
a.dtype
dtype('float64')
a
array([ 1., 2., 3.])
numpy.zeros(shape, dtype=float, order='C')
Return a new array of given shape and type, filled with zeros.
長さが 3 の0ベクトルの例:
np.zeros(3)
array([ 0., 0., 0.])
The function zeros
creates an array full of zeros,
(関数 zeros
は 0 で埋まった配列を)
np.zeros((3, 4))
array([[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]])
numpy.ones(shape, dtype=None, order='C')
Return a new array of given shape and type, filled with ones.
$3 \times 4$ の1行列の例。引数をタプルにする:
np.ones((3, 4))
array([[ 1., 1., 1., 1.], [ 1., 1., 1., 1.], [ 1., 1., 1., 1.]])
the function ones
creates an array full of ones,
(関数 ones は 1 で埋まった配列を、)
np.ones((2, 3, 4), dtype=np.int16)
array([[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]], dtype=int16)
np.ones((2, 3, 4, 5))
array([[[[ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.]], [[ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.]], [[ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.]]], [[[ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.]], [[ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.]], [[ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.]]]])
配列を生成した後,その内容をすぐ後で書き換える場合には,
配列の要素を全て 0 や 1 にするのは無駄な処理になる。
そこで,要素の値が不定の状態のままで、指定した大きさの配列を生成する関数 np.empty()
がある。
numpy.empty(shape, dtype=float, order='C')
Return a new array of given shape and type, without initializing entries.
and the function empty
creates an array whose initial content is random and depends on the state of the memory.
(関数 empty
はメモリの状態に依存したランダムな内容の配列を作成する。)
By default, the dtype
of the created array is float64
.
(デフォルトで、作成された配列の dtype
は float64
である。)
emp = np.empty((2, 3))
emp
array([[ 0., 0., 0.], [ 0., 0., 0.]])
emp.dtype
dtype('float64')
To create sequences of numbers,
NumPy provides a function analogous to range
that returns arrays instead of lists
(数値のシークエンスを作成するために、
NumPy は、リストの代わりに配列を返す、rangeに似た関数を用意している。)
np.arange(10, 30, 5)
array([10, 15, 20, 25])
np.arange(0, 2, 0.3)
array([ 0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])
When arange
is used with floating point arguments,
it is generally not possible to predict the number of elements obtained,
due to the finite floating point precision.
(arangeが、浮動小数点数を引数として用いられる場合、
浮動小数点の精度が有限であるため、一般に、得られる要素数を予測することはできない。)
For this reason,
it is usually better to use the function linspace
that receives as an argument the number of elements that we want, instead of the step
(このため、ステップの代わりに必要な要素数を引数として渡せる関数linspace
を使ったほうが大抵良い):
np.linspace(0, 2, 9) # 9 numbers from 0 to 2
array([ 0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ])
x = np.linspace(0, 2 * np.pi, 100) # 100 numbers from 0 to 2pi [rad]
print(x)
[ 0. 0.06346652 0.12693304 0.19039955 0.25386607 0.31733259 0.38079911 0.44426563 0.50773215 0.57119866 0.63466518 0.6981317 0.76159822 0.82506474 0.88853126 0.95199777 1.01546429 1.07893081 1.14239733 1.20586385 1.26933037 1.33279688 1.3962634 1.45972992 1.52319644 1.58666296 1.65012947 1.71359599 1.77706251 1.84052903 1.90399555 1.96746207 2.03092858 2.0943951 2.15786162 2.22132814 2.28479466 2.34826118 2.41172769 2.47519421 2.53866073 2.60212725 2.66559377 2.72906028 2.7925268 2.85599332 2.91945984 2.98292636 3.04639288 3.10985939 3.17332591 3.23679243 3.30025895 3.36372547 3.42719199 3.4906585 3.55412502 3.61759154 3.68105806 3.74452458 3.8079911 3.87145761 3.93492413 3.99839065 4.06185717 4.12532369 4.1887902 4.25225672 4.31572324 4.37918976 4.44265628 4.5061228 4.56958931 4.63305583 4.69652235 4.75998887 4.82345539 4.88692191 4.95038842 5.01385494 5.07732146 5.14078798 5.2042545 5.26772102 5.33118753 5.39465405 5.45812057 5.52158709 5.58505361 5.64852012 5.71198664 5.77545316 5.83891968 5.9023862 5.96585272 6.02931923 6.09278575 6.15625227 6.21971879 6.28318531]
f = np.sin(x)
print(f)
[ 0.00000000e+00 6.34239197e-02 1.26592454e-01 1.89251244e-01 2.51147987e-01 3.12033446e-01 3.71662456e-01 4.29794912e-01 4.86196736e-01 5.40640817e-01 5.92907929e-01 6.42787610e-01 6.90079011e-01 7.34591709e-01 7.76146464e-01 8.14575952e-01 8.49725430e-01 8.81453363e-01 9.09631995e-01 9.34147860e-01 9.54902241e-01 9.71811568e-01 9.84807753e-01 9.93838464e-01 9.98867339e-01 9.99874128e-01 9.96854776e-01 9.89821442e-01 9.78802446e-01 9.63842159e-01 9.45000819e-01 9.22354294e-01 8.95993774e-01 8.66025404e-01 8.32569855e-01 7.95761841e-01 7.55749574e-01 7.12694171e-01 6.66769001e-01 6.18158986e-01 5.67059864e-01 5.13677392e-01 4.58226522e-01 4.00930535e-01 3.42020143e-01 2.81732557e-01 2.20310533e-01 1.58001396e-01 9.50560433e-02 3.17279335e-02 -3.17279335e-02 -9.50560433e-02 -1.58001396e-01 -2.20310533e-01 -2.81732557e-01 -3.42020143e-01 -4.00930535e-01 -4.58226522e-01 -5.13677392e-01 -5.67059864e-01 -6.18158986e-01 -6.66769001e-01 -7.12694171e-01 -7.55749574e-01 -7.95761841e-01 -8.32569855e-01 -8.66025404e-01 -8.95993774e-01 -9.22354294e-01 -9.45000819e-01 -9.63842159e-01 -9.78802446e-01 -9.89821442e-01 -9.96854776e-01 -9.99874128e-01 -9.98867339e-01 -9.93838464e-01 -9.84807753e-01 -9.71811568e-01 -9.54902241e-01 -9.34147860e-01 -9.09631995e-01 -8.81453363e-01 -8.49725430e-01 -8.14575952e-01 -7.76146464e-01 -7.34591709e-01 -6.90079011e-01 -6.42787610e-01 -5.92907929e-01 -5.40640817e-01 -4.86196736e-01 -4.29794912e-01 -3.71662456e-01 -3.12033446e-01 -2.51147987e-01 -1.89251244e-01 -1.26592454e-01 -6.34239197e-02 -2.44929360e-16]
# math.pi とnumpy.piは同じなのか
import math
math.pi == np.pi
True
np.pi is math.pi
False
np.zeros_like(a, dtype=None)
Return an array of zeros with the same shape and type as a given array.
この例では, $2 \times 3$ の行列 a と同じ大きさの 0行列を生成する:
a = np.array([[1, 2, 3], [2, 3, 4]])
np.zeros_like(a)
array([[0, 0, 0], [0, 0, 0]])
np.zeros_like(c)
array([[ 0.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j]])
numpy.ones_like(a, dtype=None, order='K', subok=True)
Return an array of ones with the same shape and type as a given array.
np.ones_like(c)
array([[ 1.+0.j, 1.+0.j], [ 1.+0.j, 1.+0.j]])
numpy.empty_like(a, dtype=None, order='K', subok=True)
Return a new array with the same shape and type as a given array.
np.empty_like(c)
array([[ 1.+0.j, 1.+0.j], [ 1.+0.j, 1.+0.j]])
n
は、行列の大きさを表す。
例えば,4 と指定すると,単位行列は正方行列なので、
大きさ $4 \times 4$ の行列を指定したことになる:
np.identity(4)
array([[ 1., 0., 0., 0.], [ 0., 1., 0., 0.], [ 0., 0., 1., 0.], [ 0., 0., 0., 1.]])
np.random.rand()
0.21997621052048966
np.random.rand(1)
array([ 0.86422861])
np.random.rand(2)
array([ 0.41223578, 0.29693131])
np.random.rand(2, 3)
array([[ 0.98882755, 0.13003944, 0.28143098], [ 0.51028739, 0.27926848, 0.32342224]])
np.random.rand(2, 2, 3)
array([[[ 0.63080113, 0.50483757, 0.84039243], [ 0.79466475, 0.89700236, 0.11939009]], [[ 0.40637348, 0.4668876 , 0.27641308], [ 0.60587571, 0.75736269, 0.78786795]]])
np.random.randn()
-0.22012588467163624
np.random.randn(2)
array([-1.78002013, 0.57691838])
N = {'mu': 3, 'var': 6.25}
N['mu'] + np.sqrt(N['var']) * np.random.randn(2, 3) # 正規分布N の乱数の(2,3)行列
array([[ 2.21352905, 7.75438726, 7.75521993], [ 0.51149575, 5.99145576, 4.81005954]])
def ij(i, j):
return i + j
np.fromfunction(ij, (3, 3))
array([[ 0., 1., 2.], [ 1., 2., 3.], [ 2., 3., 4.]])
When you print an array, NumPy displays it in a similar way to nested lists, but with the following layout: 配列を表示する場合、 NumPyはネストされたリストと似たような表示をするが、 次のようなレイアウトになる。
(最後の軸は左から右へ表示される)、
(最後から二番目の軸は上から下へ表示される)、
(残りは上から下へ、空行で区切られて表示される)
One-dimensional arrays are then printed as rows, (1次元配列は、行(rows)のように表示され、)
a = np.arange(6) # 1次元配列
print(a)
[0 1 2 3 4 5]
bidimensionals as matrices (2次元配列は、行列(matrix)のように表示され、)
b = np.arange(12).reshape(4, 3) # 2次元配列
print(b)
[[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]]
and tridimensionals as lists of matrices (3次元配列は、行列のリストのように表示される。)
c = np.arange(24).reshape(2, 3 , 4) # 3次元配列
print(c)
[[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] [[12 13 14 15] [16 17 18 19] [20 21 22 23]]]
If an array is too large to be printed, NumPy automatically skips the central part of the array and only prints the corners(もし、配列が表示するのに大きすぎるなら、 NumPy は自動で、配列中央部分をスキップして、端部分のみを表示する):
print(np.arange(10000))
[ 0 1 2 ..., 9997 9998 9999]
print(np.arange(10000).reshape(100, 100))
[[ 0 1 2 ..., 97 98 99] [ 100 101 102 ..., 197 198 199] [ 200 201 202 ..., 297 298 299] ..., [9700 9701 9702 ..., 9797 9798 9799] [9800 9801 9802 ..., 9897 9898 9899] [9900 9901 9902 ..., 9997 9998 9999]]
To disable this behaviour and force NumPy to print the entire array,
you can change the printing options using set_printoptions
.
(この振舞いをNumPyに配列全体を表示させるために無効にするには、set_printoptions
を用いて印字オプションを変更することができる。)
np.set_printoptions(threshold=100)
print(np.arange(101))
[ 0 1 2 ..., 98 99 100]
np.set_printoptions(threshold=1000)
print(np.arange(101))
[ 0 1 2 3 4 5 6 7 8 9 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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100]
Arithmetic operators on arrays apply elementwise. 配列に対する算術演算子は、要素毎に適用され、
A new array is created and filled with the result. 演算結果が入った新たな配列が作成される。
a = np.array([20, 30, 40, 50])
a
array([20, 30, 40, 50])
b = np.arange(4)
b
array([0, 1, 2, 3])
c = a - b # 引き算
c
array([20, 29, 38, 47])
b ** 2 # 二乗
array([0, 1, 4, 9])
10 * np.sin(a)
array([ 9.12945251, -9.88031624, 7.4511316 , -2.62374854])
a < 35 # boolを返す
array([ True, True, False, False], dtype=bool)
Unlike in many matrix languages, the product operator * operates elementwise in NumPy arrays. (多くの行列言語とは異なり、 NumPy の配列においては乗算演算子 * は要素単位の演算を行う。)
The matrix product can be performed using the dot function or method (行列の積は dot 関数か method を用いて計算できる。):
A = np.array([
[1, 1],
[0, 1]
])
A
array([[1, 1], [0, 1]])
B = np.array([
[2, 0],
[3, 4]
])
B
array([[2, 0], [3, 4]])
A * B # 要素毎(elementwise)の積
array([[2, 0], [0, 4]])
A.dot(B) # 行列の積(matrix product)(method版)
array([[5, 4], [3, 4]])
np.dot(A, B) # another matrix product(function版)
array([[5, 4], [3, 4]])
Some operations, such as +=
and *=
,
act in place to modify an existing array rather than create a new one.
(+=
, *=
のような演算では、新しい配列を作るというより、すでに存在する配列の内容を書き換える。)
a = np.ones((2,3), dtype=int)
a
array([[1, 1, 1], [1, 1, 1]])
a *= 3
a
array([[3, 3, 3], [3, 3, 3]])
b = np.random.random((2,3))
b
array([[ 0.6050557 , 0.63689238, 0.42338643], [ 0.51202953, 0.77875615, 0.45499617]])
b += a
b
array([[ 3.6050557 , 3.63689238, 3.42338643], [ 3.51202953, 3.77875615, 3.45499617]])
a += b # b is not automatically converted to integer type(bは自動的にint型に変換されない)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-85-1738f4ac7f17> in <module>() ----> 1 a += b # b is not automatically converted to integer type(bは自動的にint型に変換されない) TypeError: Cannot cast ufunc add output from dtype('float64') to dtype('int32') with casting rule 'same_kind'
When operating with arrays of different types, (異なるtypeの配列を演算する場合、 )
the type of the resulting array corresponds to the more general or precise one (a behavior known as upcasting). (配列の演算結果のtype は、より一般的もしくはより精度の高い側に対応する。(アップキャスティングとして知られる振舞い))
a = np.ones(3, dtype=np.int32)
a.dtype.name
'int32'
b = np.linspace(0, np.pi, 3)
b
array([ 0. , 1.57079633, 3.14159265])
b.dtype.name
'float64'
c = a + b
c
array([ 1. , 2.57079633, 4.14159265])
c.dtype.name
'float64'
c * 1j
array([ 0.+1.j , 0.+2.57079633j, 0.+4.14159265j])
d = np.exp(1 + c * 1j)
d
array([ 1.46869394+2.28735529j, -2.28735529+1.46869394j, -1.46869394-2.28735529j])
d.dtype
dtype('complex128')
Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the ndarray
class.
(配列に含まれる全要素の総和の計算など、多くの単項演算子(unary operations)は、
ndarray
クラスのメソッドとして実装されている。)
a = np.random.random((2,3))
a
array([[ 0.11597674, 0.63910212, 0.17833459], [ 0.35632003, 0.69038429, 0.59595888]])
a.sum() # 合計
2.5760766509773951
a.min() # 最小値
0.11597673870747105
a.max() # 最大値
0.69038429053268313
By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. デフォルトで、これらの演算は、配列に対し、配列のshape に関わらず、 数値のリストであるかのように適用される。
However, by specifying the axis parameter you can apply an operation along the specified axis of an array(しかし、軸パラメータを指定することで、配列の特定の軸に沿って演算を適用することできる):
b = np.arange(12).reshape(3,4)
b
array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])
b.sum(axis=0) # sum of each column(各列の合計)
array([12, 15, 18, 21])
b.sum(axis=1) # min of each row(各行の最小値)
array([ 6, 22, 38])
b.min(axis=1) # (各業に沿った累積和)
array([0, 4, 8])
b.cumsum(axis=1) # cumulative sum along each row
array([[ 0, 1, 3, 6], [ 4, 9, 15, 22], [ 8, 17, 27, 38]], dtype=int32)
NumPy provides familiar mathematical functions such as sin
, cos
, and exp
.
(NumPyはsin, cos, exp のようなおなじみの数学関数も用意している。)
In NumPy, these are called “universal functions”(ufunc). (NumPyでは、これらは「ユニバーサル関数(ufunc)」と呼ばれる。)
Within NumPy, these functions operate elementwise on an array, producing an array as output. (NumPyの中では、これらの関数は配列の要素毎に演算を行い、 出力として新しい配列を生成する。)
B = np.arange(3)
B
array([0, 1, 2])
np.exp(B)
array([ 1. , 2.71828183, 7.3890561 ])
np.sqrt(B)
array([ 0. , 1. , 1.41421356])
C = np.array([2., -1., 4.])
np.add(B, C)
array([ 2., 0., 6.])
See also
np.sort(kind='quicksort')
One-dimensional arrays can be indexed, sliced and iterated over, much like lists and other Python sequences. (** 1次元配列 ** は、リストや他のPythonシーケンスとほぼ同様、indexでアクセスしたり、スライスしたり、イテレートすることができる。)
a = np.arange(10) ** 3
a
array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729], dtype=int32)
a[2] # index
8
a[2:5] # slice
array([ 8, 27, 64], dtype=int32)
a[:6:2] = -1000 # equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000
a
array([-1000, 1, -1000, 27, -1000, 125, 216, 343, 512, 729], dtype=int32)
a[::-1] # reversed a(iterate)
array([ 729, 512, 343, 216, 125, -1000, 27, -1000, 1, -1000], dtype=int32)
for v in a: # iterate
o = (v ** (1 / 3.))
print(o)
print(type(o))
nan <class 'numpy.float64'> 1.0 <class 'numpy.float64'> nan <class 'numpy.float64'> 3.0 <class 'numpy.float64'> nan <class 'numpy.float64'> 5.0 <class 'numpy.float64'> 6.0 <class 'numpy.float64'> 7.0 <class 'numpy.float64'> 8.0 <class 'numpy.float64'> 9.0 <class 'numpy.float64'>
C:\Miniconda3\lib\site-packages\ipykernel\__main__.py:2: RuntimeWarning: invalid value encountered in power from ipykernel import kernelapp as app
Multidimensional arrays can have one index per axis. 多次元配列は軸ごとにindex を1つ持つ。
These indices are given in a tuple separated by commas(これらのindexは、カンマ区切りのタプルで与えられる):
def f(i, j):
return 10 * i + j
b = np.fromfunction(f, (5, 4), dtype=int)
b
array([[ 0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33], [40, 41, 42, 43]])
b[2, 3] # index
23
b[0:5, 1] # slice, each row in the second column of b
array([ 1, 11, 21, 31, 41])
b[ : , 1] # equivalent to the previous example 前の行と同じ
array([ 1, 11, 21, 31, 41])
b[1:3, : ] # each column in the second and third row of b
array([[10, 11, 12, 13], [20, 21, 22, 23]])
When fewer indices are provided than the number of axes, the missing indices are considered complete slices: (与えられたindex の数が軸数より少ない場合、足りないindexは、完全なスライスと見なされる)
b[-1] # == b[-1, : ], the last row.
array([40, 41, 42, 43])
The expression within brackets in b[i]
is treated as an i followed by as many instances of :
as needed to represent the remaining axes.
(b[i]
のブラケット(大かっこ)の中の式は、i の後に残りの軸を表現するのに必要な分の :
が続いているものとして扱われる。)
NumPy also allows you to write this using dots as b[i,...]
.
(NumPyではドットを用いてこれを b[i,...]
と書いてもいい。)
The dots (...
) represent as many colons as needed to produce a complete indexing tuple.
(ドット (...) は完全な添字タプルを生成するために必要な分のコロンを表す。)
For example, if x
is a rank 5 array (i.e., it has 5 axes), then
(例えば、もし、x
がrank 5の配列(即ち、軸が5つ)であるとするなら)、
x[1, 2, ...]
is equivalent to x[1, 2, :, :, :]
,
x[..., 3]
to x[:, :, :, :, 3]
and
x[4, ..., 5, :]
to x[4, :, :, 5, :]
.
c = np.array( [[[ 0, 1, 2], # a 3D array (two stacked 2D arrays) shape(2,2,3)
[ 10, 12, 13]],
[[100,101,102],
[110,112,113]]])
c.shape
(2, 2, 3)
c[1, ...] # same as c[1,:,:] or c[1]
array([[100, 101, 102], [110, 112, 113]])
c[..., 2] # same as c[:,:,2]
array([[ 2, 13], [102, 113]])
Iterating over multidimensional arrays is done with respect to the first axis (多次元配列のイテレートは最初の軸に関して行われる):
for row in b: # iterate
print(row)
[0 1 2 3] [10 11 12 13] [20 21 22 23] [30 31 32 33] [40 41 42 43]
However, if one wants to perform an operation on each element in the array,
one can use the flat
attribute which is an iterator over all the elements of the array
(しかし、配列の各要素についてある演算を行いたい場合には、
配列の全要素を渡り歩くイテレータであるflat属性が使える):
for element in b.flat:
print(element)
0 1 2 3 10 11 12 13 20 21 22 23 30 31 32 33 40 41 42 43
np.ndarray
の1次元と2次元の配列と,数学の概念であるベクトルと行列との関係についての補足。
線形代数では,縦(行)ベクトルや横(列)ベクトルという区別があるが、
1次元の np.ndarray
配列にはそのような区別はない。
そのため,1次元配列を転置することができず、数学でいうところのベクトルとは厳密には異なる。
col = np.array([1, 2, 3, 4, 5])
col
array([1, 2, 3, 4, 5])
col.T # 転置されない
array([1, 2, 3, 4, 5])
行ベクトルや列ベクトルを区別して表現するには、 行数が1である2次元配列(リストが2重)を用いる。 縦ベクトルは次のようになり:
col = np.array([[1, 2, 3, 4, 5]]) # 列ベクトル
col
array([[1, 2, 3, 4, 5]])
col.T # 転置すると行ベクトルになる
array([[1], [2], [3], [4], [5]])
See also:
a = np.array([
[1, 2],
[3, 4]
])
for index, v in np.ndenumerate(a):
print(index, v)
(0, 0) 1 (0, 1) 2 (1, 0) 3 (1, 1) 4
grid = np.indices((2, 3))
grid.shape
(2, 2, 3)
grid
array([[[0, 0, 0], [1, 1, 1]], [[0, 1, 2], [0, 1, 2]]])
grid[0] # row indices
array([[0, 0, 0], [1, 1, 1]])
grid[1] # column indices
array([[0, 1, 2], [0, 1, 2]])
print(np.random.get_state())
('MT19937', array([ 142035591, 2992053589, 1436206245, 2075584926, 1153473185, 2023702678, 164400302, 1487550030, 2500935688, 398450423, 2241243447, 3053850279, 992651537, 703626941, 184754581, 896494976, 1383230003, 2643832555, 3134902701, 1111739025, 2920121130, 623667065, 2369835178, 1833405942, 2809490491, 3070134211, 1141359642, 2096071536, 2435951546, 3145324780, 3116839452, 958673918, 3956765171, 1987654081, 2421401012, 3770752022, 3728506922, 647936218, 1368833425, 1170918621, 256711212, 565537722, 47683647, 902979579, 4236163335, 2979348143, 586206835, 2089696176, 896873745, 791857444, 2015898658, 2804859506, 3046071113, 1269391123, 31875726, 286279086, 651550258, 3547868609, 3735096567, 2444283478, 2711698963, 3033889294, 3454923815, 2983951799, 2195132295, 1178883285, 4024891227, 3152655913, 1958647164, 4257009190, 4025369694, 3828126802, 1873509363, 1720662462, 2212066546, 455762541, 3793163378, 644909654, 559814422, 2981159863, 2661623634, 3535510456, 844281027, 490535964, 1081261424, 3359141009, 938517146, 3356810585, 130787175, 599435927, 3092043225, 4241934958, 1016131312, 2927980932, 2010138871, 2518721969, 4094107020, 610754650, 3954153848, 159930682, 2987042834, 3721426071, 2645092560, 1355115469, 3413014711, 1944376166, 3461189383, 3917334290, 74695030, 2850087777, 707777319, 2516827815, 3224771949, 1141485812, 3171420957, 672485961, 459879657, 912596249, 663957204, 5918518, 1103621813, 501944213, 1631096881, 3122860076, 2278630995, 1209874428, 3744380314, 805023017, 1925639328, 736276791, 1947857217, 1882766030, 4257232545, 2499697969, 3285125239, 1885861871, 2961227433, 3239844188, 476830246, 357690197, 2092642040, 113119071, 2200290090, 764879910, 670953681, 1059284608, 1680368602, 136045864, 520938361, 1763018900, 3883730164, 3079424491, 755438962, 996289528, 3317809914, 3710175121, 287431291, 1664427713, 2096871603, 2197536088, 3105003241, 2090557734, 966646221, 2569763368, 1545600799, 3857029860, 656123340, 3847674313, 2214159386, 3857745392, 2245805411, 1462515455, 2163503196, 2857156793, 3621005311, 4256842092, 1155733147, 1125803240, 1767579638, 68928065, 1671689657, 1997372333, 498924339, 3576617021, 1013107959, 2827611360, 2794339670, 209571897, 1338550303, 361512031, 3754572, 652743540, 3519093460, 739889437, 1111465341, 3251485047, 362148944, 2206196524, 985862922, 3929751624, 3578420643, 1146794489, 843188314, 2610325699, 514280443, 3291531068, 3794394289, 2122818980, 369436833, 1951135533, 739985190, 441883207, 1389631440, 1350924293, 1546985811, 3248905716, 3468017355, 1569406733, 3835309206, 2912654368, 1528722370, 2827965180, 3520486755, 1248565327, 3125477371, 413493895, 3163916452, 725296147, 3569812165, 3594060977, 223769852, 4016913123, 199649659, 2387872526, 2232099730, 1017629739, 3763043326, 553275367, 1776501529, 1337103914, 3611725888, 1816757911, 3990050011, 1284084626, 3960383656, 829247461, 884246041, 4099054010, 2147958793, 2790310388, 3725027202, 2047836473, 2699620237, 1625135648, 3480810772, 507563469, 3320881602, 3531411735, 1912341960, 1635437378, 3675849063, 3792767455, 53301134, 1576145667, 2928897288, 1619873387, 1134829289, 2937405113, 2990424722, 960044927, 441606876, 2440907884, 1538411584, 2055481117, 4124939760, 3930986978, 346900338, 3119371365, 4226580917, 2035090841, 1209401160, 2987739125, 4219373111, 2563890038, 3453779645, 2354575556, 2685667126, 3282193026, 1370359443, 729245177, 1449464241, 2176356266, 3547819587, 497243031, 2240013424, 3111489103, 3637367624, 4219434555, 3327925904, 2110342492, 1574503668, 3516032106, 2365786000, 2136289405, 4220226430, 3767276806, 699927949, 1009560737, 1498612251, 183140526, 2313403360, 2609148251, 1562475327, 1136309454, 2507993653, 2721628382, 539775799, 2608168597, 107664588, 91058698, 2966320812, 1268597914, 2767767069, 2322258733, 255361300, 336973049, 611589367, 319867770, 3501940199, 2917296194, 2611612347, 3410720766, 2461276906, 2374375340, 3297874812, 46968096, 3156597219, 2301873843, 1215765093, 1565322310, 4231408440, 1236025328, 3998002477, 3216345736, 2579061465, 133375714, 3283182695, 3897317582, 1419982699, 820452103, 4199742771, 286486733, 3515446310, 1765780165, 595913573, 1591261177, 2328334743, 3970052466, 1516808160, 4016541804, 3666318903, 2407791524, 1523542227, 2370124516, 1747425004, 1537426418, 407514393, 211538908, 3875078012, 3653001925, 451251581, 3352305342, 2651370878, 3226077856, 1230576020, 1099768802, 3259751470, 1970069530, 509019668, 3366323700, 2926137302, 3981858952, 4021659285, 619849168, 4215963354, 2984258796, 3851392388, 3158425985, 3560817656, 2250106785, 3206971482, 1655938903, 273422088, 3506736879, 3691541393, 3747164664, 1284273582, 2810760774, 3130282239, 3521838548, 3479537299, 1729692646, 786506497, 1366221618, 3858955132, 1343494639, 1546780048, 2686682139, 678294543, 1175681977, 4187815499, 4044112559, 3800305097, 485424669, 968893753, 3932571578, 4020402031, 1002653103, 2658597689, 1101714886, 894430014, 3384807671, 181496754, 600008401, 389772502, 4123780972, 100565123, 250056669, 2083544624, 295455779, 577114333, 4265480163, 2448689604, 2185555125, 1542098544, 1607705911, 3347715220, 2868801558, 312467210, 2807484054, 3257776610, 3115662801, 4063024529, 3798742742, 1222666812, 2940413477, 935910877, 3136225329, 922962398, 151534858, 1446714361, 2180239133, 1024393977, 284862041, 3724636482, 1486941761, 3427128826, 3660018510, 1503210988, 4109626410, 728386886, 1398943888, 718286078, 4208402410, 1189727972, 790637034, 514415175, 2534820247, 1123228716, 23001759, 4082188812, 2392061683, 1431433791, 1409961516, 1948716618, 4223370697, 2129109461, 2407060028, 4056760945, 2287892234, 4189456823, 2575306936, 2285330651, 3762811416, 1918613495, 381829954, 680576880, 3679272033, 1420265841, 654426530, 2143017384, 1500689788, 3578824987, 535425024, 376400650, 1380266383, 1667345437, 1631624298, 2952264329, 3123649135, 142551326, 594501007, 300344446, 3481166875, 236327910, 1242977005, 1505960258, 2423519855, 2274266816, 645961304, 380544684, 399849397, 3258669357, 1925352863, 2962881697, 3851387278, 2592270930, 37628778, 2076754228, 3872413202, 3281442657, 3507194069, 3061024331, 3485217810, 1762507053, 3238625115, 775753689, 3957571808, 2635345357, 2226946715, 2512941414, 3440087588, 19857156, 577436620, 1818870068, 4085000082, 590010247, 1636648937, 718782902, 3653737921, 3938746433, 3027456748, 324088840, 3177565598, 4277326312, 1547345075, 2757352137, 795386085, 2498226824, 1371257679, 692346877, 3700231927, 4130090397, 3748672208, 2056006452, 1479361294, 1971091411, 2738837275, 1250147263, 3988554168, 1735000973, 2245087787, 207499281, 1405366959, 2633088501, 4134913239, 1735215863, 781386546, 4069333371, 2504283036, 2093545768, 3858025633, 4055885329, 1048810190, 3472525613, 2026515774, 387219462, 3127423286, 2387070541, 2151227874, 612749484, 3196725532, 2605738273, 3641366231, 1173524352, 1029028169, 3975451221, 240705905, 2516290939, 329644749, 3518899331, 1323774035, 3476585380, 86964699, 1934246442, 952099776, 670385401, 3401150768, 302066928, 842978659, 2764670271, 2937450353, 2761196917, 3018308041, 1886997152, 147548092, 1486528689, 191796765, 401876355, 3285745255, 2649150337, 3560516779, 1659943257, 2444357490, 1477501373, 2160692004, 1268424486, 2884722778, 3729914941, 2086156973, 2372656643, 3234926284, 1542964012, 2445238322], dtype=uint32), 96, 1, -1.5159457205911733)