Search code examples
pythonarraysnumpynumpy-ndarray

Arrays of size 0 in NumPy


I need to work with arrays that can have zeros in their shapes. However, I am encountering an issue. Here's an example:

import numpy as np

arr = np.array([[]])
assert arr.shape == (1,0)
arr.reshape((1,0))  # No problem (nothing changes)
arr.reshape((-1,0))  # ValueError: cannot reshape array of size 0 into shape (0)

I always thought that -1 for a reshape operation means the product of all the remaining dimensions, i.e., 1 in this case. Is this a bug, or am I not understanding how this should work?


Solution

  • If you read the documentation:

    One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

    As furas says, it can't automatically calculate the remaining dimension because of undefined division by 0. Any number times 0 is 0.

    arr.reshape((1,0)) # Works
    arr.reshape((3,0)) # Works too!
    arr.reshape((42,0)) # Works too!
    

    Arguably, the error message thrown by NumPy is not the clearest though, and it is factually wrong:

    arr.reshape(0) # Works as well
    

    So you actually can "reshape array of size 0 into shape (0)". And it should say something along the lines of "undefined reshape requested" instead...

    So it is not a "bug", but definitely a wart, IMO. It might be worth reporting if you feel like it :)