科学の箱

科学・IT・登山の話題

Python

すべての要素が同じ値を持つ配列を生成

投稿日:

配列はリストから生成できるが、numpyでは様々な方法で目的とする配列を生成できる。

  • すべての要素が0である配列の生成
  • すべての要素が1である配列の生成
  • すべての要素が同じ値である配列の生成

すべての要素が0である配列の生成

すべての要素を0にするためにはnumpy.zeros()を利用する。

numpy.zeros

必ず必要となる引数はshapeであり、配列の次元を指定する。

print(np.zeros((3, 6)))
# [[0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0.]]
print(np.zeros((3, 6)).dtype)
# float64

またdtypeを指定することで要素の型も指定できる。

print(np.zeros((3, 6),dtype=np.int8).dtype)
# int8

 

すべての要素が1である配列の生成

zerosと同様にすべての要素が1である配列はnumpy.ones()で生成できる。

print(np.ones((3, 6)))
#[[1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1.]]

print(np.ones((3, 6)).dtype)
# float64

dtypeを指定することで型を変更できる。

print(np.ones((3, 6), dtype=np.int8).dtype)
# int8

 

すべての要素が同じ値である配列の生成

すべての要素が同じ値である配列はnumpy.full()を使用する。

shapeには配列の次元をシーケンス型で引き渡す。設定したい値はfull_valueである。

print(np.full((3,5),3.14))
# [[3.14 3.14 3.14 3.14 3.14]
 [3.14 3.14 3.14 3.14 3.14]
 [3.14 3.14 3.14 3.14 3.14]]

 

 

メタ情報

inarticle



メタ情報

inarticle



-Python
-

執筆者:


comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

関連記事

no image

python virtualenvの使い方

pip3 install virtualenv virtualenv myenv myenv/Scripts/activate Related posts:automated the boring – …

no image

複数のグラフを表示する方法

ここでは以下を説明する。 複数のグラフを表示する2つの方法 サブプロットのグラフを整形 複数のグラフを表示する 複数のグラフを表示するためには二通りの方法がある。 subplots()を使ってあらかじ …

no image

automated the boring – day8

https://automatetheboringstuff.com/chapter15/ さてプログラムを実行しているときに案外出てくる要件が時間計測。 例えばアルゴリズム間でパフォーマンスを比較す …

no image

特定のパッケージのためのgitignoreを作成したい

https://gitignore.ioを開く パッケージ名を入力 Createをクリック Related posts:numpyで配列を抜き出す方法PythonでMicrosoft Visual C …

no image

SIGNATE お弁当の需要予測-3

Seabornを利用してデータをビジュアル化してみる。 まずは売り上げの分布図から sns.distplot(d_train[‘y’], kde=False, rug=False, bins=50) …

2019年9月
« 8月   10月 »
 1
2345678
9101112131415
16171819202122
23242526272829
30  

side bar top



アーカイブ

カテゴリー