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 in Python by Gita
616 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 by Faiza

Related Questions In Python

0 votes
1 answer

How can I convert a list of dictionaries from a CSV into a JSON object in Python?

You could try using the AST module. ...READ MORE

answered Apr 17, 2018 in Python by anonymous
729 views
+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 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 282 views
+4 votes
6 answers
+1 vote
2 answers
0 votes
1 answer