LoginSignup
0
1

More than 3 years have passed since last update.

【python】numpy.empty 初期値設定

Posted at

numpyで初期値設定をするときにいつも numpy.zeros か numpy.ones しか使ってなかった。
この他にも初期値設定する方法 numpy.empty があったので書く。
また、初期値設定の使い方を確認する。

環境

linux
pyhton

numpy.empty

これの引数↓

numpy.empty(shape, dtype=float, order='C')

実験1
引数に何も持たせない。

>>> import numpy
>>> numpy.empty()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: empty() missing required argument 'shape' (pos 1

shapeの引数がないというエラーが出る。

実験2
shapeを持たせる。

>>> import numpy
>>> numpy.empty(shape=1)
array([0.])
>>> numpy.empty(shape=2)
array([-5.73021895e-300,  6.93125508e-310])
>>> numpy.empty(shape=3)
array([0., 0., 0.])
>>> numpy.empty(shape=4)
array([0., 0., 0., 0.])
>>> numpy.empty(shape=5)
array([4.66352184e-310, 4.03179200e-313, 4.66352172e-310, 5.54048513e+228,
       7.56680154e+168])
>>> numpy.empty(shape=6)
array([4.66352179e-310, 5.72938864e-313, 6.93125428e-310, 6.93125428e-310,
       0.00000000e+000, 1.16707455e-072])
>>> numpy.empty((2,3))
array([[4.66352179e-310, 5.72938864e-313, 6.93125428e-310],
       [6.93125428e-310, 0.00000000e+000, 1.16707455e-072]])
>>> numpy.empty(5.6)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer

できた。。。このことから、shape=はなくても良い、数字に少数はできない、初期値はshapeによってすべての値が0になることもある、ということがわかった。

実験3
dtypeを持たせる。実験1からshapeは必須ということが分かるのでshapeも持たせた。

>>> import numpy
>>> numpy.empty(2,dtype=float)
array([-5.73021895e-300,  6.93125508e-310])
>>> numpy.empty(2,dtype=int)
array([-9093133594791772939,      140290164735896])
>>> numpy.empty(2,int)
array([130238442063002869,    140290164735896])

このことから、dtypeをfloatにしたら初期値が少数に、intにしたら初期値が整数になることがわかる。また、引数のdtype=の部分は省略してもよいこととが numpy.empty(2,int) からわかる。

実験4
order='C'を変える。

>>> import numpy
>>> numpy.empty(2,dtype=float,order='C')
array([-5.73021895e-300,  6.93125508e-310])
>>> numpy.empty(2,dtype=float,order='F')
array([5.73021895e-300, 6.93125508e-310])
>>> numpy.empty(2,dtype=float,order='E')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: order must be one of 'C', 'F', 'A', or 'K' (got 'E')
>>> numpy.empty(2,dtype=float,order='A')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: only 'C' or 'F' order is permitted

このことから、order='C'かorder='F'しか使えないことが分かる。また、order='C'とorder='F'の違いは見られなかった。そのため、どちらでも良いのではないかと思った。

0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1