MAC
MAC

Reputation: 1533

Padding using Numpy in Python

Takes one 3-dimensional array. Pad the instances from the end position as shown in the example below. That is, I need to pad the reflection of the utterance mirrored along the edge values of the array.

Array a:

array ([array([[3, 1, 4, 1],
   [5, 9, 2, 6],
   [5, 3, 5, 8]]),
   array([[9, 7, 9, 3],
   [2, 3, 8, 4]]),
   array([[6, 2, 6, 4],
   [3, 3, 8, 3],
   [2, 7, 9, 5],
   [0, 2, 8, 8]])], dtype=object)

dim1 = a.shape[0]    # n
dim2 = max([i.shape[0] for i in a]) # m
dim3 = a[0].shape[1] # k

Dimension of final matrix after padding:

result = np.zeros((dim1, dim2, dim3))

Output:

      [[[3. 1. 4. 1.]
        [5. 9. 2. 6.]
        [5. 3. 5. 8.]
       [5. 3. 5. 8.]]
      [[9. 7. 9. 3.]
       [2. 3. 8. 4.]
       [2. 3. 8. 4.]
       [9. 7. 9. 3.]]

      [[6. 2. 6. 4.]
       [3. 3. 8. 3.]
       [2. 7. 9. 5.]
       [0. 2. 8. 8.]]]

how can I get the output using numpy.pad?

Upvotes: 0

Views: 329

Answers (1)

Poe Dator
Poe Dator

Reputation: 4913

The trick is to use pad_width parameter with specific number of lines ot be padded at each dimension. In this case pad_width should have shape (2,2).

for b in a:
    extra_lines = dim2 - b.shape[0]
    c = np.pad(b, pad_width=[[0, extra_lines], [0, 0]], mode='symmetric')
    print(c, '\n')

[[3 1 4 1]
 [5 9 2 6]
 [5 3 5 8]
 [5 3 5 8]] 

[[9 7 9 3]
 [2 3 8 4]
 [2 3 8 4]
 [9 7 9 3]] 

[[6 2 6 4]
 [3 3 8 3]
 [2 7 9 5]
 [0 2 8 8]] 

Upvotes: 1

Related Questions