Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k 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 (25.1k points)
edited by

Here is a better way to do 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)

If you want to learn more about numpy check out this video: 

Browse Categories

...