Remrinのpython攻略日記

python3に入門しました。python3についてあれこれとサンプルコードとか。

NumPyの使い方(17) 構造化配列

NumPyの構造化配列(structured array)について。
 
dtypeを自分で設定して、異なる型の変数を織り込める。
フィールド名で要素を参照できる。

dtype = [("x", int), ("y", float)]
a1 = np.array([(1, 2), (3, 4), (5, 6)], dtype=dtype)

print(a1)      # [(1, 2.0) (3, 4.0) (5, 6.0)]
print(a1["x"]) # [1 3 5 ]
print(a1["y"]) # [ 2.  4.  6.]

 
フィールドのsizeを指定したりもできる。

dtype = [("x", int, 3), ("y", float)]

a2= np.array(([1, 2, 3], 4), dtype=dtype)
print(a2["y"]) # 4.0

a3 = np.zeros(5, dtype=dtype)
print(a3["x"])
# [[0 0 0]
#  [0 0 0]
#  [0 0 0]
#  [0 0 0]
#  [0 0 0]]

print(a3["y"]) # [ 0.  0.  0.  0.  0.]

 
フィールドのネストもできる。

print(a3["y"]) # [ 0.  0.  0.  0.  0.]

dtype = [("x", [("y", float), ("z", int)]), ("a", int)]
a4 = np.array([((1, 2), 3), ((4, 5), 6)], dtype=dtype)
print(a4["x"])      # [(1.0, 2) (4.0, 5)]
print(a4["x"]["z"]) # [2 5]