Bolajio
Bolajio

Reputation: 127

Tuple error (numpy)

I padded my data using np.pad(x,[(0,0)], mode='constant') and got this error:

ValueError: Unable to create correctly shaped tuple from [(0, 0).

My x has shape (21, 4) and I want to pad it to get a shape of (22,4).

Does anyone know what is happening?

Upvotes: 4

Views: 5206

Answers (1)

John1024
John1024

Reputation: 113814

The rank of the first argument has to match the number of pairs in the second argument.

For example, observe that this gives the error that you see:

>>> x = np.ones((21, 4))
>>> np.pad(x, [(0,0)], mode='constant')
Traceback (most recent call last):
  [...snip...]
ValueError: Unable to create correctly shaped tuple from [(0, 0)]

The problem is that x has rank 2 but the second argument has only one pair, not two.

However, if we supply a second argument with two pairs, this succeeds:

>>> x2 = np.pad(x, [(0,0), (0,0)], mode='constant')

To get the final dimension that you want, we have to pad the first dimension by 1. One way to do that is:

>>> x2 = np.pad(x, [(0,1), (0,0)], mode='constant')
>>> x2.shape
(22, 4)

Upvotes: 2

Related Questions