Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy C-API: convert type object to type number

The function

PyObject* PyArray_TypeObjectFromType(int);

converts the type number for a NumPy scalar type (NPY_BOOL, NPY_BYTE, ...) to the corresponding type object.

How do you do the opposite conversion, from the type object for a NumPy scalar type to the corresponding type number?

Edit: The following code is based on kwatford's answer. It accepts both type objects such as int and numpy.int16, and strings such as "int", u"int" and "int16".

int numpyScalarTypeNumber(PyObject* obj)
{
    PyArray_Descr* dtype;
    if(!PyArray_DescrConverter(obj, &dtype)) return NPY_NOTYPE;
    int typeNum = dtype->type_num;
    Py_DECREF(dtype);
    return typeNum;
}
like image 573
Johan Råde Avatar asked Dec 12 '11 16:12

Johan Råde


People also ask

How do I change the Dtype of a numpy array?

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.

What is numpy C API?

NumPy provides a C-API to enable users to extend the system and get access to the array object for use in other routines. The best way to truly understand the C-API is to read the source code. If you are unfamiliar with (C) source code, however, this can be a daunting experience at first.

What is U32 data type in numpy?

dtype='<U32' is a little-endian 32 character string. The documentation on dtypes goes into more depth about each of the character. 'U' Unicode string.

What is Dtype object in numpy?

A data type object (an instance of numpy. dtype class) describes how the bytes in the fixed-size block of memory corresponding to an array item should be interpreted. It describes the following aspects of the data: Type of the data (integer, float, Python object, etc.)


1 Answers

If you can get PyArray_Descr structs rather than PyArray_TypeObjects, you can simply look at the type_num field. The descr structs can be acquired via the type number using PyArray_DescrFromType. If you look at that link, there are also a few more functions for converting various things into descr structs. They're probably more useful in general than the type objects, and they contain references to their types as well.

like image 188
kwatford Avatar answered Sep 28 '22 00:09

kwatford