logo

Python で NumPy を使用して空の行列を作成するにはどうすればよいですか?

用語 空の行列 行も列もありません。欠損値を含む行列には、ゼロを含む行列と同様に、少なくとも 1 つの行と列があります。 数値Python ( ナムピー ) は、Python で数値配列と行列を操作するための便利な機能を豊富に提供します。 NumPy を使用して空の行列を作成したい場合。関数を使用できます。

    numpy.empty numpy.zeros

1. numpy.empty : エントリを初期化せずに、指定された形状と型の新しい配列を返します。



構文: numpy.empty(shape, dtype=float, order=’C’)

パラメーター:

  • 形状:int または int のタプル、つまり配列 (5,6) または 5 の形状。
  • dtype データ型、オプション、つまり配列に必要な出力データ型 (例: numpy.int8)。デフォルトはnumpy.float64です。
  • order{‘C’, ‘F’}、オプション、デフォルト: ‘C’、つまり、多次元データを行優先 (C スタイル) または列優先 (Fortran スタイル) の順序でメモリに保存するかどうか。

空の行列 5 x 5 を作成する例を考慮して、NumPy の空の関数を使ってみましょう。



例 1: 5 列 0 行の空の行列を作成するには:

Python3




文字列の連結



import> numpy as np> > > x>=> np.empty((>0>,>5>))> print>(>'The value is :'>, x)> > # if we check the matrix dimensions> # using shape:> print>(>'The shape of matrix is :'>, x.shape)> > # by default the matrix type is float64> print>(>'The type of matrix is :'>, x.dtype)>

>

>

ラテックステーブル

出力:

The value is : [] The shape of matrix is : (0, 5) The type of matrix is : float64>

ここで、行列は 0 行 5 列で構成されているため、結果は「[ ]」になります。 NumPy の空関数の別の例を見てみましょう。乱数を含む空の行列 4 x 2 を作成する例を考えてみましょう。

例 2: 予想される次元/サイズを使用して空の配列を初期化します。

Python3




# import the library> import> numpy as np> > # Here 4 is the number of rows and 2> # is the number of columns> y>=> np.empty((>4>,>2>))> > # print the matrix> print>(>'The matrix is : '>, y)> > # print the matrix consist of 25 random numbers> z>=> np.empty(>25>)> > # print the matrix> print>(>'The matrix with 25 random values:'>, z)>

>

>

出力:

マトリックスは次のとおりです。
[[1.41200958e-316 3.99539825e-306]
[3.38460865e+125 1.06264595e+248]
[1.33360465e+241 6.76067859e-311]
[1.80734135e+185 6.47273003e+170]]

25 個のランダム値を含む行列: [1.28430744e-316 8.00386346e-322 0.00000000e+000 0.00000000e+000
0.00000000e+000 1.16095484e-028 5.28595592e-085 1.04316726e-076
1.75300433e+243 3.15476290e+180 2.45128397e+198 9.25608172e+135
4.73517493e-120 2.16209963e+233 3.99255547e+252 1.03819288e-028
2.16209973e+233 7.35874688e+223 2.34783498e+251 4.52287158e+217
8.78424170e+247 4.62381317e+252 1.47278596e+179 9.08367237e+223
1.16466228e-028]

ここでは、行列が乱数で満たされるように行と列の数を定義します。

メソッドJavaに等しい

2. numpy.zeros : 指定された形状と型の、ゼロで埋められた新しい配列を返します。

構文: numpy.zeros(shape, dtype=float, order=’C’)

パラメーター:

  • shape : int または int のタプル、つまり配列 (5,6) または 5 の形状。
  • dtype データ型、オプション、つまり配列に必要な出力データ型 (例: numpy.int8)。デフォルトは numpy.float64 です。
  • order{‘C’, ‘F’}、オプション、デフォルト: ‘C’、つまり、多次元データを行優先 (C スタイル) または列優先 (Fortran スタイル) の順序でメモリに保存するかどうか。

ゼロを含む行列を作成する例を考慮して、NumPy の zeros 関数を始めましょう。

例: 7 列 5 行のゼロ行列を作成するには:

Python3


Cで文字列を反転する



import> numpy as np> x>=> np.zeros((>7>,>5>))> > # print the matrix> print>(>'The matrix is : '>, x)> > # check the type of matrix> x.dtype>

>

>

出力:

The matrix is : [[0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.]] dtype('float64')>