Create a Numpy scalar from dtype

Viewed 9229

I'm trying to create a numpy scalar of a specified dtype. I know I could do, say, x = numpy.int16(3), but I don't know the dtype in advance.

If I were to want an array then

dtype = int
x = numpy.array(3, dtype=dtype)

would do it, so I had high hopes for

x = numpy.generic(3, dtype=dtype)

but one cannot create an instance of numpy.generic.

Any ideas?

3 Answers

As commented, the accepted answer is not generally correct for all dtypes, for example timedeltas:

In [6]: d = np.dtype("timedelta64[10m]")

In [7]: d.type(3)
Out[7]: numpy.timedelta64(3)

To always get the correct answer use the following:

In [8]: np.array(3, d)[()]
Out[8]: numpy.timedelta64(3,'10m')

In case someone would like to get the dtype from a string, you can use

import numpy as np
val = np.dtype('int32').type(3.0)
Related