1

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)?

Gulzar
  • 23,452
  • 27
  • 113
  • 201

2 Answers2

3

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')
user2357112
  • 260,549
  • 28
  • 431
  • 505
  • Thanks! Still, how would I get my desired result of shape (200,1)? – Gulzar Jun 02 '19 at 09:34
  • 1
    @Gulzar: Do you want a 1D array or not? You don't seem to have a clear understanding of the difference between a 1D array and a 1-row 2D array - you say you want a 1D array, and you try to work with it as if there is no length-1 dimension, but then you say you want a 2D shape. You should figure that out first. – user2357112 Jun 02 '19 at 09:49
  • you are correct. I didn't realize the difference. What I really want is a single row, 2D array. – Gulzar Jun 02 '19 at 09:53
  • 1
    actually, `(200, 1)` would be a 1-*column* 2D array. I'll add code for both 1-row and 1-column. – user2357112 Jun 02 '19 at 10:13
  • correct again... sorry about that... I do need a column array. (200,1) is the final desired size – Gulzar Jun 02 '19 at 10:14
  • 2
    Answer expanded. – user2357112 Jun 02 '19 at 10:19
0
  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:

enter image description here

Community
  • 1
  • 1
AyiFF
  • 127
  • 1
  • 1
  • 7
  • I think you stated different ways to get the result I don't want. How to get the result I DO want? – Gulzar Jun 02 '19 at 09:25