Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I want to know how I can pad a 2D numpy array with zeros using python 2.6.6 with numpy version 1.5.0. Sorry! But these are my limitations. Therefore I cannot use np.pad. For example, I want to pad a with zeros such that its shape matches b. The reason why I want to do this is so I can do:

b-a

such that

>>> a 

array([[ 1., 1., 1., 1., 1.], 

[ 1., 1., 1., 1., 1.], 

[ 1., 1., 1., 1., 1.]]) 

>>> b 

array([[ 3., 3., 3., 3., 3., 3.], 

[ 3., 3., 3., 3., 3., 3.], 

[ 3., 3., 3., 3., 3., 3.], 

[ 3., 3., 3., 3., 3., 3.]]) 

>>> c 

array([[1, 1, 1, 1, 1, 0], 

[1, 1, 1, 1, 1, 0], 

[1, 1, 1, 1, 1, 0], 

[0, 0, 0, 0, 0, 0]])

The only way I can think of doing this is appending, however, this seems pretty ugly. is there a cleaner solution possibly using b.shape?

I had to clean it up a bit, and this is what I got:

def pad(array, reference_shape, offsets): 

""" array: Array to be padded 

reference_shape: tuple of size of ndarray to create 

offsets: list of offsets (number of elements must be equal 

to the dimension of the array) will throw a ValueError if 

offsets is too big and the reference_shape cannot handle 

the offsets """ 

# Create an array of zeros with the reference shape 

result = np.zeros(reference_shape) 

# Create a list of slices from offset to offset + shape in 

each dimension 

insertHere = [slice(offsets[dim], offsets[dim] + 

array.shape[dim]) for dim in range(array.ndim)] 

# Insert the array in the result at the specified offsets 

result[insertHere] = array 

return result

1 Answer

0 votes
by (106k points)

It is very simple to pad numpy array with zeros, you need to create an array containing zeros using the reference shape:

result = np.zeros(b.shape) 

result = np.zeros_like(b) 

After that you need to insert the array where you need it:

result[:a.shape[0],:a.shape[1]] = a

print(result) 

Output:-

array([[ 1., 1., 1., 1., 1., 0.], [ 1., 1., 1., 1., 1., 0.], 

[ 1., 1., 1., 1., 1., 0.], [ 0., 0., 0., 0., 0., 0.]])

To Learn what is Python and python applications then visit this python for data science course.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Sep 27, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...