Pythonのnumpy.zeros()関数

Pythonのnumpy.zeros()関数は、指定された形状とタイプの新しい配列を返します。要素の値は0です。

「numpy.zeros()」関数の引数

numpy.zeros()関数の構文は次のとおりです。

zeros(shape, dtype=None, order='C')
  • The shape is an int or tuple of ints to define the size of the array.
  • The dtype is an optional parameter with default value as float. It’s used to specify the data type of the array, for example, int.
  • The order defines the whether to store multi-dimensional array in row-major (C-style) or column-major (Fortran-style) order in memory.

Pythonのnumpy.zeros()の例

「numpy zeros() 関数を使用して、配列を作成する例をいくつか見てみましょう。」

0で初期化された一次元配列を作成する。

import numpy as np

array_1d = np.zeros(3)
print(array_1d)

以下のものを日本語で別の表現にしてください:
出力:

[0. 0. 0.]

要素がデフォルトデータ型としてfloatを持っていることに気付いてください。そのため、ゼロは0です。

2. 多次元配列の作成

import numpy as np

array_2d = np.zeros((2, 3))
print(array_2d)

出力:

[[0. 0. 0.]
 [0. 0. 0.]]

3. intデータ型を持つNumPyのゼロ配列

import numpy as np

array_2d_int = np.zeros((2, 3), dtype=int)
print(array_2d_int)

出力:

[[0 0 0]
 [0 0 0]]

4. タプルデータ型とゼロで構成されたNumPy配列。

私たちは、配列の要素をタプルとして指定し、それらのデータ型も指定することができます。

import numpy as np

array_mix_type = np.zeros((2, 2), dtype=[('x', 'int'), ('y', 'float')])
print(array_mix_type)
print(array_mix_type.dtype)

日本語です

[[(0, 0.) (0, 0.)]
 [(0, 0.) (0, 0.)]]
[('x', '<i8'), ('y', '<f8')]
Numpy Zeros Python

参照:API ドキュメント

コメントを残す 0

Your email address will not be published. Required fields are marked *