python numpyで二次元配列を作成する

python numpyで二次元配列を作成する

pythonで、ライブラリnumpyのarrayを使用して、二次元配列を作成するサンプルコードを記述してます。pythonのバージョンは3.8.5を使用してます。

環境

  • OS windows10 pro 64bit
  • python 3.8.5

numpyインストール

numpyをインストールされていない方は、pipでインストールしておきます。

pip install numpy

# Successfully installed numpy-1.19.4

二次元配列を作成

array関数を使用すると二次元配列を作成することが可能です。

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print(arr)
# [[1 2 3]
#  [4 5 6]
#  [7 8 9]]

以下のように、作成することも可能です。

import numpy as np

arr1 = ["a", "b", "c"]
arr2 = ["d", "e", "f"]
arr3 = ["g", "h", "i"]

arr = np.array([arr1, arr2, arr3])

print(arr)

# [['a' 'b' 'c']
#  ['d' 'e' 'f']
#  ['g' 'h' 'i']]

reshape関数で、行列数を指定して作成することも可能です。

import numpy as np

arr1 = ["a", "b", "c", "d", "e", "f"]


arr = np.array(["a", "b", "c", "d", "e", "f"]).reshape(3, 2)

print(arr)

[['a' 'b']
 ['c' 'd']
 ['e' 'f']]