Could anyone tell me how to check the data type of an ndarray
that has been passed to C code?
In the concrete example I would like to call a different function if the datatype of the array is float32
or double/float64
. So something like
if( Dtype(MyArray) == NPY_FLOAT )
{
DoSomething_float( MyArray );
}
else
{
DoSomething_double( MyArray );
}
I already found
PyTypeNum_ISFLOAT(num)
PyDataType_ISFLOAT(descr)
PyArray_ISFLOAT(obj)
In the numpy C API, but I don't understand how to use those. I've already tried to find an instructive example but have found none.
Well, you can get the element type of the array: Type type = array. GetType(). GetElementType();
Array in C can be defined as a method of clubbing multiple entities of similar type into a larger group. These entities or elements can be of int, float, char, or double data type or can be of user-defined data types too like structures.
An array type is a user-defined data type consisting of an ordered set of elements of a single data type. An ordinary array type has a defined upper bound on the number of elements and uses the ordinal position as the array index.
There are three different kinds of arrays: indexed arrays, multidimensional arrays, and associative arrays.
you are almost there, as you are looking for PyArray_TYPE
:
int typ=PyArray_TYPE(MyArray);
switch(typ) {
case NPY_FLOAT:
DoSomething_single(MyArray);
break;
case NPY_DOUBLE:
DoSomething_double(MyArray);
break;
default:
error("unknown type %d of MyArray\n", typ);
}
The long, convoluted way of doing this, if you are dealing with a PyArrayObject* arr
, would be to check arr->descr->type
or arr->descr->type_num
which holds:
char PyArray_Descr.type
A traditional character code indicating the data type
int PyArray_Descr.type_num
A number that uniquely identifies the data type. For new data-types, this number is assigned when the data-type is registered
As @umlauete answer points out, there are cleaner ways of incorporating that into your code, but it is always a good thing to know what's in your PyArrayObject
and PyArray_Descr
structs. And always "read the docs, Luke!"
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