Python Error ""ValueError: could not broadcast input array from shape (4) into shape (1000)""

0 votes

I have the following python code:

big_array = np.zeros(shape=(100,100), dtype=np.uint8) 
mini_square = np.ones(shape=(2,2), dtype=np.uint8) 

flattened_array = np.ravel(big_array) 
flattened_minisquare = np.ravel(mini_square) 

flattened_array[1:-1:10] = flattened_minisquare

I get the following error:

"ValueError: could not broadcast input array from shape (4) into shape (1000)"
Jun 13, 2019 in Python by Gita
8,972 views
What exactly are you trying to do?
I'm trying to insert a small array into a larger one without resizing.

1 answer to this question.

0 votes

There are better ways of achieving the same. Have a look at this:

import numpy as np

big_array = np.zeros(shape=(100,100), dtype=np.uint8)
mini_square = np.ones(shape=(2,2), dtype=np.uint8) 

flattened_array = np.ravel(big_array)
flattened_minisquare = np.ravel(mini_square)

stepsize = 10
temp = np.zeros(stepsize + len(flattened_minisquare) - 1)
temp[-len(flattened_minisquare):] = flattened_minisquare

mask = np.copy(temp)
mask[-len(flattened_minisquare):] = np.ones_like(flattened_minisquare)
mask = ~mask.astype(bool)

out = np.resize(temp, len(flattened_array))
final_mask = np.resize(mask, len(flattened_array))
out[final_mask] = flattened_array[final_mask]

print(out)
#[0. 0. 0. ... 0. 0. 0.]
answered Jun 13, 2019 by Faiza

Related Questions In Python

0 votes
1 answer

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

Hey @Giorgio, You can try this hope this ...READ MORE

answered Feb 18 in Python by Gitika
• 29,690 points
845 views
+1 vote
0 answers

ValueError: could not broadcast input array from shape (2) into shape (5)

I was implementing gillespie algorithm and when ...READ MORE

Dec 23, 2019 in Python by anonymous
• 130 points

reshown Jan 13 by Kalgi 1,103 views
0 votes
1 answer
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 963 views
0 votes
0 answers
+4 votes
6 answers
+1 vote
3 answers
0 votes
1 answer

Python error "AttributeError: incompatible shape for a non-contiguous array"

It is not always possible to change ...READ MORE

answered May 29, 2019 in Python by Imran
227 views