[Numpy-discussion] Can PyArray_CastTo be used to "subcast" an array of float to int

David Cournapeau david at ar.media.kyoto-u.ac.jp
Mon Jan 15 23:48:23 CST 2007


David Cournapeau wrote:
> Hi,
>
>     I would like to convert a double array to an *existing* array of 
> int32 using the C numpy API. I tried using PyArray_CastTo, but this 
> gives me an array full of zeros instead of converting the items to int. 
> I am doing something like the following to convert a PyArrayObject in_o 
> of double:
>
>     ndescr  = PyArray_DescrNewFromType(NPY_INT32);
>    
>     /* should be equivalent to astype */
>     ar  = (PyArrayObject*)PyArray_FromArray((PyArrayObject*)in_o, 
> ndescr, NPY_FORCECAST);
>     if (ar == NULL) {
>         goto clean_ndescr;
>     }
>     /* Using C Api for casting */
>     dims    = PyArray_DIMS(in_o);
>     Py_INCREF(ndescr);
>     casted  = (PyArrayObject*)PyArray_Zeros(((PyArrayObject*)in_o)->nd, 
> dims, ndescr, 0);
>     if (casted == NULL) {
>         goto clean_ar;
>     }
>     st  = PyArray_CastTo((PyArrayObject*)in_o, casted);
>     if (st) {
>         goto clean_casted;
>     }
Just forget about it, I didn't notice that PyArray_CastTo takes its 
input as the 2d argument...

Sorry for the noise,

David


More information about the Numpy-discussion mailing list