Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in Python by (47.6k points)

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)"

1 Answer

0 votes
by (106k points)
edited by

You can use the below-mentioned code which is much better ways of achieving the same:-

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.]

To know more about this you can have a look at the following video:-

Browse Categories

...