ValueError: operands could not be broadcast together with shapes (5,) (30,)

twi picture twi · Nov 13, 2017 · Viewed 23.5k times · Source

I am trying to merge arrays like this:

If:

a = [1.2, 1, 3, 4]
b = [0.0 , 0.0]
c = [0.0 , 0.0]
a = a + b + c

Then the result should be:

[0.0 , 0.0 , 1.2 , 1 ,3 ,4 , 0.0 ,0.0]

what I do is that extract histogram of array and merge it with normal array.

x1, bins, patch = plt.hist(array1, bins = round(max(array1) - min(array1)))
x1 = b + x1 + c

but the form of x1 is 
x1 = [  2.   0.   0.   1.   0.   2.   5.   0.   1.   1.   0.   1.   5.]

and maybe that cause the error like this

ValueError: operands could not be broadcast together with shapes (5,) (30,)

please help me. I don't know what to do

Answer

BenT picture BenT · Nov 13, 2017

You could use np.concatenate to to do this but you can also do this by converting your arrays to lists.

import numpy as np

a = list(np.array([1.2, 1, 3, 4]))
b = list(np.array([0.0 , 0.0]))
c = list(np.array([0.0 , 0.0]))
D= a + b + c

So in you code try:

x1 = list(b) + list(x1) + list(c)

#Put it back into a numpy array
x1 = np.array(x1)