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?
In NumPy, a scalar is any object that you put in an array. It's similar to the concept in linear algebra, an element of a field which is used to define a vector space. NumPy ensures all scalars in an array have same types. It's impossible one scalar having type int32, the other scalars having type int64.
Python defines only one type of a particular data class (there is only one integer type, one floating-point type, etc.). This can be convenient in applications that don't need to be concerned with all the ways data can be represented in a computer.
Any type object with a dtype attribute: The attribute will be accessed and used directly. The attribute must return something that is convertible into a dtype object. Several kinds of strings can be converted.
In order to change the dtype of the given array object, we will use numpy. astype() function. The function takes an argument which is the target data type. The function supports all the generic types and built-in types of data.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With