科学の箱

科学・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でpostgresqlを使うときに必要なモジュール

pip install psycopg2-binary Related posts:python data scientist bootcamp配列を利用した四則演算とuniversal関数kaggl …

no image

pipインストールでエラーが出る場合

pipインストールでエラーが出る場合 Collecting tensorflow WARNING: Retrying (Retry(total=4, connect=None, read=None, …

no image

kaggle Titanic Tutorial – 2

決定木を利用して分析する。 データの作成 y_train = d_train["Survived"].values x_train = d_train[["Pclass& …

no image

automated the boring – day8

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

no image

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

https://gitignore.ioを開く パッケージ名を入力 Createをクリック Related posts:python data scientist bootcampnumpy.aran …

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

side bar top



アーカイブ

カテゴリー