ozi
ozi

Reputation: 1691

force new numpy arrays to be as type float

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

Answers (2)

0x90
0x90

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

U2EF1
U2EF1

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

Related Questions