互换的青春
import numpy as npdef blockshaped(arr, nrows, ncols): """ Return an array of shape (n, nrows, ncols) where n * nrows * ncols = arr.size If arr is a 2D array, the returned array looks like n subblocks with each subblock preserving the "physical" layout of arr. """ h, w = arr.shape return (arr.reshape(h//nrows, nrows, -1, ncols) .swapaxes(1,2) .reshape(-1, nrows, ncols))def unblockshaped(arr, h, w): """ Return an array of shape (h, w) where h * w = arr.size If arr is of shape (n, nrows, ncols), n sublocks of shape (nrows, ncols), then the returned array preserves the "physical" layout of the sublocks. """ n, nrows, ncols = arr.shape return (arr.reshape(h//nrows, -1, nrows, ncols) .swapaxes(1,2) .reshape(h, w))例如,c = np.arange(24).reshape((4,6))print(c)# [[ 0 1 2 3 4 5]# [ 6 7 8 9 10 11]# [12 13 14 15 16 17]# [18 19 20 21 22 23]]print(blockshaped(c, 2, 3))# [[[ 0 1 2]# [ 6 7 8]]# [[ 3 4 5]# [ 9 10 11]]# [[12 13 14]# [18 19 20]]# [[15 16 17]# [21 22 23]]]print(unblockshaped(blockshaped(c, 2, 3), 4, 6))# [[ 0 1 2 3 4 5]# [ 6 7 8 9 10 11]# [12 13 14 15 16 17]# [18 19 20 21 22 23]]它以不同的格式(使用更多的轴)排列块,但是它的优点是(1)始终返回视图,并且(2)能够处理任何尺寸的数组。
一只甜甜圈
希望我对你说得对,假设我们有a,b:>>> a = np.array([[1,2] ,[3,4]])>>> b = np.array([[5,6] ,[7,8]]) >>> a array([[1, 2], [3, 4]]) >>> b array([[5, 6], [7, 8]])为了使其成为一个大的二维数组,请使用numpy.concatenate:>>> c = np.concatenate((a,b), axis=1 )>>> carray([[1, 2, 5, 6], [3, 4, 7, 8]])