7

I'm really new to the numpy and currently confused with negative values in reshape.

import numpy as np

a=np.arange(6)
c=a.reshape(1,3,2)
d=a.reshape(-1,3,2)
e=a.reshape(-1,1,2)
print c
print
print d
print
print e

and it returns

[[[0 1]
  [2 3]
  [4 5]]]

[[[0 1]
  [2 3]
  [4 5]]]

[[[0 1]]

 [[2 3]]

 [[4 5]]]

The question here is that when comparing c and d, there's no difference at all. However in e, additional empty line is formed between each row. So, what exactly does the -1 do in reshape function, and why it causes empty lines between each row in e? Thanks !

2
  • It is asked before and here is a good explanation: Commented Sep 18, 2017 at 14:23
  • I clearly acknowledge that but that doesn't give me explanation on empty lines. That is what i am curious about Commented Sep 18, 2017 at 15:42

2 Answers 2

9

When you add -1 to an axis in numpy it will just put everything else in that axis. This is, for an array a of shape (10, 10), the following operations will apply:

>>> a.reshape(-1, 10, 10) # a is (1, 10, 10)
>>> a.reshape( 1, 10, 10) # a is also (1, 10, 10)
>>> a.reshape(-1, 5, 5)   # a is (4, 5, 5), since 4 * 5 *  5 = 100
>>> a.reshape(-1, 5, 10)  # a is (2, 5, 10) since 2 * 5 * 10 = 100 

This is, when reshaping the total number of elements must be the same, so adding -1 to the shape just lets numpy calculate the remaining value for you, so that the product of the axes still matches the previous number of elements.

Sign up to request clarification or add additional context in comments.

Comments

2

The difference between c and e is not only the additional space, but also the additional bracket around each pair, i.e.

[2 3]    vs    [[2 3]]

This is because the shape of c is [1, 3, 2], while the shape of e is [3, 1, 2]. The shape of d is also [1, 3, 2], and that is why c and d are equal.

When you put -1 in the shape, numpy infers it from the other dimensions, that is replaces -1 with product of all dimensions of a / product of all specified shapes

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.