Skip to content Skip to sidebar Skip to footer

Numpy.array's Have Bizarre Behavior With /= Operator?

I'm trying to normalize an array of numbers to the range (0, 1] so that I can use them as weights for a weighted random.choice(), so I entered this line: # weights is a nonzero num

Solution 1:

It's because numpy cares the type. When you apply the division, you're changing int to float. But numpy won't let you do that! That's why your values should be already in float. Try this:

>>>a = np.array([1.0,2.0,3.0])>>>a /= sum(a)>>>a
array([0.16666667, 0.33333333, 0.5       ])

But why did the other one work? It's because that's not an "in-place" operation. Hence a new memory location is being created. New variable, new type, hence numpy doesn't care here.

Post a Comment for "Numpy.array's Have Bizarre Behavior With /= Operator?"