0

I came across this strange behavior when dealing with numpy arrays

x = np.array([[0,3,6],
             [1,5,10]])
print(x[1]/3)
x[1]=x[1]/3
print(x[1])

Output is as shown below:

[0.33333333 1.66666667 3.33333333]
[0 1 3]

Why is it different? And how can I assign [0.33333333 1.66666667 3.33333333] to x[1] without rounding off the values?

  • Consider the type which elements in x bear. Dividing the array allows answers to be cast to another type. What happens when you reassign? – Josh Purtell Sep 08 '20 at 20:58

1 Answers1

4

Numpy arrays have fixed types, determined at the time when the array is created. All elements of your original array have type int. The division results in a floating-point array, but when you assign this back to the integer array, the floating point numbers need to be rounded.

To fix this, you should start with a floating-point array right away, e.g.

x = np.array([[0, 3, 6], [1, 5, 10]], dtype=float)

(Adding a decimal point to any of the numbers in the array also works.)

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • So, is there any way I can change the array to 'float' after first creating the array as 'int'? – Pranav Katta Sep 09 '20 at 07:49
  • @PranavKatta The easiest option is to create a new array from the existing one, e.g. with `x = x.astype(float)`. This will copy the array to a new one, but since the data needs to be converted anyway, this generally doesn't cause any additional overhead. An in-place conversion only works if the sizes of the data types match – see [In-place type conversion of a NumPy array](https://stackoverflow.com/questions/4389517/in-place-type-conversion-of-a-numpy-array) for that case. – Sven Marnach Sep 09 '20 at 08:06