Here’s another fun little example regarding numpy indices.
import numpy as np
array = np.array([1, 2])
print(array)
[1 2]
Now, I’m trying to assign a new value to the first item of the array:
array[0] = 1.5
print(array)
[1 2]
This is rather unexpected.
I would have expected the following:
[1.5 2]
The issue here is that numpy automatically detects the data type that describes how the bytes in the fixed-size block of memory corresponding to an array item should be interpreted.
For more information, refer to: Data type objects (dtype) — NumPy v1.25 Manual
To fix this issue, explicitly set the dtype
when first creating the array:
array = np.array([1, 2], dtype=np.float64)
now,
array[0] = 1.5
yields the expected result.
print(array)
[1.5 2]