[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
Tue Jan 16 00:34:36 EST 2007
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;
}
When using this code in python with a = numpy.linspace(0, 10, 101)
as input, I got array([0, 0, 1, 1, 2, 2, 3, 3, 4, 5] for ar, and
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) for array casted.
Can't PyArray_CastTo be used to 'unsafely' cast an array, or is
there something I am missing ?
cheers,
David
More information about the NumPy-Discussion
mailing list