我有一个3d numpy数组(数据),形状如(103,37,13)。我想通过在每个轴的两个方向上几乎相等的零填充将这个numpy数组的大小调整为(250,250,13)。
下面的代码适用于2d数组,但我无法使其适用于3d数组。
>>> a = np.arange(6)
>>> a = a.reshape((2, 3))
>>> np.lib.pad(a, [(2,3),(1,1)], 'constant', constant_values=[(0, 0),(0,0)])
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 1, 2, 0],
[0, 3, 4, 5, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
>>> zerpads =np.zeros(13)
>>> data1=np.lib.pad(data,[(73,74),(106,107)],'constant',constant_values=[(zerpads, zerpads),(zerpads,zerpads)])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/ayush/anaconda2/lib/python2.7/site-packages/numpy/lib/arraypad.py", line 1295, in pad
pad_width = _validate_lengths(narray, pad_width)
File "/home/ayush/anaconda2/lib/python2.7/site-packages/numpy/lib/arraypad.py", line 1080, in _validate_lengths
normshp = _normalize_shape(narray, number_elements)
File "/home/ayush/anaconda2/lib/python2.7/site-packages/numpy/lib/arraypad.py", line 1039, in _normalize_shape
raise ValueError(fmt % (shape,))
ValueError: Unable to create correctly shaped tuple from [(73, 74), (106, 107)]
答案 0 :(得分:2)
data1=np.pad(data, ((73,74), (106,107), (0, 0)), 'constant')
工作正常。需要为第三轴添加第3组对。