one can assign a probability to each element of an array by simply deviding the value of each element by the sum of all array elements. I am trying to do this with python for a long list of numpy arrays. My Code:
def calc_probs(self, array_list):
for array in array_list:
buffer=array.astype("float")
s=sum(buffer)
for e in np.nditer(buffer, op_flags=["readwrite"]):
e/=s
self.probs.append(buffer)
This code should be working. In fact it IS working when typing it into the interactive mode of IPython. The results are then just what I want them to be. But if I save the code to a file und run, I always get the following ValueError:
ValueError: non-broadcastable output operand with shape () doesn’t match the broadcast shape (10)
I do not understand why this error occures, especially when running from a file. Could anyone please explain it to me and help to solve the problem?
Thanks a lot!
sumis__builtin__.sum, which doesn’t know how to sum a NumPy array so just returns the array unchanged. The error is happening because you are trying to divide the singular matrixeby the 10×10 matrixs.You want
s = np.sum(buffer).This whole code could be simplified to: