Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Numpy scalar from dtype

Tags:

python

numpy

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?

like image 971
n00b Avatar asked Dec 27 '13 17:12

n00b


People also ask

What is NumPy scalar type?

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.

How do you define a scalar in Python?

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.

Is Dtype an attribute?

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.

How do I change Dtype to NP?

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.


1 Answers

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
like image 142
NPE Avatar answered Sep 17 '22 13:09

NPE