描述:我想将一个二维数组转为三维数组,具有有如下规则,首先,A数组维度为6*4(注意,我这里的A数组不止一个,假设有n个),B数组维度为3*4(只有一个),按照网上的办法,我想对n个A数组和1个B数组进行拼接得到一个三位数组。
在帖子上的大部分做法仅有两个数组进行拼接,使用到的是hstack等,我这里是n91个数组增加维度
我原本使用的是下列方法:
import numpy as np
ls = []
# 假设n为2
for i in range(2):
A = np.reshape(np.arange(24), (6, 4))
ls.append(A)
B = np.reshape(np.arange(12), (3, 4))
ls.append(B)
print(np.array(ls).shape)
C = np.reshape(np.array(ls), (-1, 4))
print(C)
但是报错如下
(3,)
Traceback (most recent call last):
File "D:/Lan/LinkRecover/1.5_BTLink增加降维/ttt.py", line 17, in <module>
C = np.reshape(np.array(ls), (-1, 4))
File "<__array_function__ internals>", line 180, in reshape
File "D:\ProgramData\Miniconda3\lib\site-packages\numpy\core\fromnumeric.py", line 298, in reshape
return _wrapfunc(a, 'reshape', newshape, order=order)
File "D:\ProgramData\Miniconda3\lib\site-packages\numpy\core\fromnumeric.py", line 57, in _wrapfunc
return bound(*args, **kwds)
ValueError: cannot reshape array of size 3 into shape (4)
此处可见由于A数组和B数组维度分别为6*4和3*4,拼接以后得到的是n+1但是后面的维度不能得到我想要的结果,由于没想到直接的办法,我只好遍历拼接,做了一个最基础的拼接,代码如下:
import numpy as np
ls = []
for i in range(2):
A = np.reshape(np.arange(24), (6, 4))
for j in A:
ls.append(j)
B = np.reshape(np.arange(12), (3, 4))
for j in B:
ls.append(j)
C = np.reshape(np.array(ls), (-1, 4))
print(C)
print('C的维度:', C.shape)
运行结果如下:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]
[20 21 22 23]
[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]
[20 21 22 23]
[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
C的维度: (15, 4)
我的实际应用场景是将batch中的数据保存出来,batch_size为8, 但是最后一个batch并不为8,所以产生了这个问题,如果有大神有简单的解决方法,求留言。