12

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?

4
  • I'm not sure what the problem is. Why doesn't x = dtype(3) do what you want? Commented Dec 27, 2013 at 17:36
  • 1
    @DSM: Strictly speaking, that doesn't do it. In the OP's example that would create int(3) instead of numpy.int32(3). Whether that's an issue or not, I don't know. Commented Dec 27, 2013 at 17:49
  • @NPE: I'm assuming that by "of a specified dtype", the OP has put the wanted dtype in dtype; int will give int, np.int16 will give np.int16. I must be missing something, though, because the OP knows that you can call the type object (in the first line) and also that you can bind the type objects to dtype. Commented Dec 27, 2013 at 17:53
  • @DSM, sorry for confusion, I have code like a = np.eye(2, dtype=int), b = np.zeros(2, dtype=a.dtype), so a.dtype can be passed as a dtype argument, but a.dtype(3) gives a not-callable error. The .type method does what I need ("make dtypes callable"). Commented Dec 27, 2013 at 18:09

3 Answers 3

11

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')
Sign up to request clarification or add additional context in comments.

1 Comment

too difficult to read:/
10

The following will create a scalar of x's dtype:

In [18]: val = x.dtype.type(3)

In [19]: val
Out[19]: 3

In [20]: type(val)
Out[20]: numpy.int32

2 Comments

Thanks - I didn't know about the .type method for dtypes
This however does not work for all dtypes nor does it preserve endian-ness for any dtype (always turns it into native endian). I believe the only way to preserve endian-ness and work with more dtypes (but probably still not all) is to create an array and get the element(s) from it.
5

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.