チャポケのブログ

勉強したことをまとめておく。

NumPy 配列の関数での初期化と、配列形状の変形

要素が同じ値の配列生成

np.zeros()関数で、すべての要素が0の配列を生成する。
np.ones()関数で、すべての要素が1の配列を生成する。

import numpy as np

# すべての要素が0の配列
aaa = np.zeros(5)
print(aaa)
# [ 0.  0.  0.  0.  0.]

aaa = np.zeros((2,3))
print(aaa)
# [[ 0.  0.  0.]
#  [ 0.  0.  0.]]

# すべての要素が1の配列
aaa = np.ones(5)
print(aaa)
# [ 1.  1.  1.  1.  1.]

aaa = np.ones((2,3))
print(aaa)
# [[ 1.  1.  1.]
#  [ 1.  1.  1.]]
 
# すべての要素が3の配列
aaa = np.ones(5) * 3
print(aaa)
# [ 3.  3.  3.  3.  3.]

等差数列の配列生成

np.arange()関数で、等差数列の配列を生成する。

import numpy as np

# 等差数列の要素の配列
aaa = np.arange(3)
print(aaa)
# [0 1 2]

aaa = np.arange(3, 7)
print(aaa)
# [3 4 5 6]

aaa = np.arange(1, 10, 2)
print(aaa)
# [1 3 5 7 9]

aaa = np.arange(10, 0, -4)
print(aaa)
# [10  6  2]

配列形状の変形

.reshape()メソッドnp.reshape()関数で、配列の形状を変形する。
この2つの動作は同じ。

import numpy as np

aaa = np.arange(12)
print(aaa)
# [ 0  1  2  3  4  5  6  7  8  9 10 11]

bbb = aaa.reshape(2,6)
print(bbb)
ccc = np.reshape(aaa, (2,6))
print(ccc)
# [[ 0  1  2  3  4  5]
#  [ 6  7  8  9 10 11]]

bbb = aaa.reshape(2,2,3)
print(bbb)
ccc = np.reshape(aaa, (2,2,3))
print(ccc)
# [[[ 0  1  2]
#   [ 3  4  5]]
# 
#  [[ 6  7  8]
#   [ 9 10 11]]]

# 全要素数と、形状指定の全要素数が不一致だとエラーValueErrorとなる。
ccc = np.reshape(aaa, (2,5))
bbb = aaa.reshape(2,5)
# ValueError: cannot reshape array of size 12 into shape (2,5)

引数-1で配列の形状指定すると、その次元のサイズは他の次元の引数から自動的に決まる値になる。

import numpy as np

aaa = np.arange(12)
print(aaa)
# [ 0  1  2  3  4  5  6  7  8  9 10 11]

bbb = aaa.reshape(2,-1)
print(bbb)
ccc = np.reshape(aaa, (-1,6))
print(ccc)
# [[ 0  1  2  3  4  5]
#  [ 6  7  8  9 10 11]]

bbb = aaa.reshape(2,-1,3)
print(bbb)
ccc = np.reshape(aaa, (2,2,-1))
print(ccc)
# [[[ 0  1  2]
#   [ 3  4  5]]
# 
#  [[ 6  7  8]
#   [ 9 10 11]]]