If you're not sure your input is going to be a Numpy array, you can use asarray
with dtype=int
instead of astype
:
>>> np.asarray([1,2,3,4], dtype=int)
array([1, 2, 3, 4])
If the input array already has the correct dtype, asarray
avoids the array copy while astype
does not (unless you specify copy=False
):
>>> a = np.array([1,2,3,4])
>>> a is np.asarray(a) # no copy :)
True
>>> a is a.astype(int) # copy :(
False
>>> a is a.astype(int, copy=False) # no copy :)
True