1

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)
lloydpick
  • 1,638
  • 1
  • 18
  • 24
eric lardon
  • 351
  • 1
  • 6
  • 21
  • 3
    Possible duplicate of [Zero pad numpy array](https://stackoverflow.com/questions/38191855/zero-pad-numpy-array) – jdehesa Apr 10 '18 at 13:25

1 Answers1

3

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')
jdehesa
  • 58,456
  • 7
  • 77
  • 121