Reputation: 1691
Every now and then I write code like this:
import numpy as np
a = np.array([1,2,3])
a[1] = 3.3
a[2] *= 50
print(a)
Here I do not intend a
to be initialized as int
, but as float
, but I forgot it.
Is there a way to make sure such initializations default to float, unless dtype is explicitly specified?
Upvotes: 3
Views: 11867
Reputation: 40982
Use the dtype
parameter see here:
>>> import numpy as np
>>> np.array([1, 2, 3], dtype=float)
array([ 1., 2., 3.])
Upvotes: 6
Reputation: 13259
Not without changing the source, no. Your options are:
Get in the habit of putting dots at the end of your numbers:
np.array([1.,2.,3.])
Use dtype
explicitly:
np.array([1,2,3], dtype=float)
Make a new function:
def ozi_array(*args, **kwargs):
if 'dtype' not in kwargs:
return np.array(*args, dtype=float, **kwargs)
return np.array(*args, **kwargs)
Upvotes: 9