【Numpy学習記録】np.stackとnp.concatenate

766 ワード

np.stackとnp.concatenateの2つの関数は配列を接続するために使用されていますが、彼らの間にはいくつかの検討点があります.直接コードをつけると、見てすぐにわかります.
 
import numpy as np

a = np.zeros(12).reshape(4,3,)
b = np.arange(12).reshape(4,3)

# for np.stack:all input arrays must have the same shape
print(np.hstack((a, b)).shape)  # (4, 6)
print(np.vstack((a, b)).shape)  # (8, 3)
print(np.dstack((a, b)).shape)  # (4, 3, 2)

print(np.stack((a, b), axis=0).shape)  # (2, 4, 3)
print(np.stack((a, b), axis=1).shape)  # (4, 2, 3)
print(np.stack((a, b), axis=2).shape)  # (4, 3, 2)

a = np.zeros(12).reshape(2,3, 2)
b = np.arange(6).reshape(2,3, 1)
print(np.concatenate((a, b), axis=2).shape)  # (2, 3, 3)
# print(np.stack((a, b), axis=2).shape)  # error
print(np.dstack((a, b)).shape)  # (2, 3, 3)