eric lardon
eric lardon

Reputation: 359

Padding a matrix with numpy

I have a 2D numpy array called adj=dim(16,16). l would like to pad it with zeros to get new_adj=dim(31,31).

I tried...

new_adj=np.pad(adj,((15,31),(31,15)),mode='constant')

However

new_adj.shape=(62, 62)

I'm supposed to get...

new_adj.shape=(31, 31)

Upvotes: 1

Views: 4755

Answers (1)

javidcf
javidcf

Reputation: 59731

If you look at the documentation of np.pad, it explains that each tuple in the second argument specifies how many positions of pad to add at the beginning and end of each dimension. You are adding 15 rows at the top and 31 at the bottom, and 31 columns at the left and 15 at the right, hence the final (62, 62) matrix. If you only want to add rows and columns at the bottom and right, do:

new_adj = np.pad(adj, [(0, 15), (0, 15)], mode='constant')

Upvotes: 3

Related Questions