Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy strange behavior past end of array

Normally, if you attempt to assign past the end of an array in numpy, the non-existent elements are disregarded.

>>> x = np.zeros(5)
>>> x[3:6] = np.arange(5)[2:5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not broadcast input array from shape (3) into shape (2)

However, the same operation entirely past the end of the array "succeeds" if only one element is assigned:

>>> x[5:] = np.arange(5)[4:]
>>> x[5:] = np.arange(5)[4:100]

This only works if the RHS has one element:

>>> x[5:] = np.arange(5)[3:]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not broadcast input array from shape (2) into shape (0)

Why is this the case? How is it possible not to get an error here? Is this behavior documented, or is it a bug?

like image 268
Mad Physicist Avatar asked Sep 12 '19 20:09

Mad Physicist


1 Answers

In keeping with Python list behavior, you can slice off-the-end. The first case shows that's true for both the LHS and RHS.

The rest is broadcasting. 3 can't got into 2. 2 can't go into 0. But 1 can go into anything, including 0. We tend to think of broadcasting replicating a size 1 dimension to something larger, but replicating to 0 also works.

like image 120
hpaulj Avatar answered Nov 09 '22 05:11

hpaulj