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
15,384 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
• 54,140 points
5,037 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,613 views
0 votes
1 answer
0 votes
0 answers

ValueError: could not broadcast input array from shape (224,224,9) into shape (224,224)

img_shape = 224 test_data = [] test_labels = [] for ...READ MORE

Nov 5 in Python by Eyosiyas
• 120 points
62 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, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,591 views
0 votes
0 answers
+4 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,800 points
1,201 views
+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
398 views