numpy pad with zeros creates 2d array instead of desired 1d

橙三吉。 提交于 2019-12-13 03:15:27

问题


I am trying to pad a 1d numpy array with zeros.

Here is my code

v = np.random.rand(100, 1)
pad_size = 100
v = np.pad(v, (pad_size, 0), 'constant')

result is 200x101 array, whose last column is [0,0,0,... <v>], (leading 100 zeros), and all 1st 100 columns are zeros.

How to get my desired array

[0,0,0,..0,<v>]

of size (len(v)+pad_size, 1)?


回答1:


The pad output is 2D because the pad input was 2D. You made a 2D array with rand for some reason:

v = np.random.rand(100, 1)

If you wanted a 1D array, you should have made a 1D array:

v = np.random.rand(100)

If you wanted a 1-column 2D array, then you're using pad incorrectly. The second argument should be ((100, 0), (0, 0)): padding 100 elements before in the first axis, 0 elements after in the first axis, 0 elements before in the second axis, 0 elements after in the second axis:

v = np.random.rand(100, 1)
pad_size = 100
v = np.pad(v, ((pad_size, 0), (0, 0)), 'constant')

For a 1-row 2D array, you would need to adjust both the rand call and the pad call:

v = np.random.rand(1, 100)
pad_size = 100
v = np.pad(v, ((0, 0), (pad_size, 0)), 'constant')



回答2:


  1. np.hstack((np.zeros((200, 100)), your v))

  2. np.concatenate((np.zeros((200, 100)), your v), axis=1)

    may be your desire this:



来源:https://stackoverflow.com/questions/56413710/numpy-pad-with-zeros-creates-2d-array-instead-of-desired-1d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!