【Python】np.stack 和 np.concatenate

np.stack 和 np.concatenate两个函数都可用来连接数组

1,np.stack


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)

2,np.concatenate

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)

猜你喜欢

转载自blog.csdn.net/qq_34106574/article/details/82752369