2

I am facing an error indicating that there are different array sizes when trying to insert values ​​into a predefined 0 values array using the slice method and for loop. In the three examples array [start:stop], stop-start=5. But a problem occurs when the start and stop values ​​are increased by +1 or decreased by -1, which is strange because as I mentioned the difference between start and stop is always the same.

Attached are three examples that I have tried, with only the third example working without a problem, while the other two show the following error: ValueError: could not broadcast input array from shape (y,1) into shape (x,1)

# First example:

arr0 = np.array([38, 78, 118, 158, 158, 198, 238, 278])
arr1 = np.array([43, 83, 123, 163, 163, 203, 243, 283])

res1 = [np.array([0, -0.5, -1, -0.5, 0])[:, None], np.array([0, -1., -2., -1., 0])[:, None]]

nod1 = np.array([0, 0, 0, 0, 1, 1, 1, 1])
out1 = []
for i in range(0, 8):
    print(i)
    out1.append(np.zeros((281, 1)))

for i, j, k, l in zip(range(0, 8), nod1, arr0, arr1):
    print(i, j, k, l)
    out1[i][k:l] = res1[j]

"Error: ValueError: could not broadcast input array from shape (5,1) into shape (3,1)"
    
# Second example:
    
arr2 = arr0 - 1
arr3 = arr1 - 1
    
out1 = []
for i in range(0, 8):
    print(i)
    out1.append(np.zeros((281, 1)))

for i, j, k, l in zip(range(0, 8), nod1, arr2, arr3):
    print(i, j, k, l)
    out1[i][k:l] = res1[j]

"Error: ValueError: could not broadcast input array from shape (5,1) into shape (4,1)"

# Third example:
    
arr4 = arr0 - 2
arr5 = arr1 - 2 

out1 = []
for i in range(0, 8):
    print(i)
    out1.append(np.zeros((281, 1)))

for i, j, k, l in zip(range(0, 8), nod1, arr4, arr5):
    print(i, j, k, l)
    out1[i][k:l] = res1[j]
    
"Passed, both sides have shape (5, 1)"

My question is what is causing this error to appear?

From what I read at Understanding slicing, one user has pointed out that:

Of course, if (stop-start)%stride != 0, then the end point will be a little lower than start-1.

, but unfortunately I can't see this in my examples.

I would ask for your help and discussion on how to overcome this problem, because the [start:stop] values ​​are important to me in order to determine the exact location to place new values ​​in the predefined array with 0 values.

bennu777
  • 21
  • 2

0 Answers0