[Numpy-discussion] Creating a bool array with Cython

Dag Sverre Seljebotn d.s.seljebotn@astro.uio...
Sat Feb 25 21:04:07 CST 2012

On 02/25/2012 03:26 PM, Keith Goodman wrote:
> Is this a reasonable (and fast) way to create a bool array in cython?
>      def makebool():
>          cdef:
>              int n = 2
>              np.npy_intp *dims = [n]
>              np.ndarray[np.uint8_t, ndim=1] a
>          a = PyArray_EMPTY(1, dims, NPY_UINT8, 0)
>          a[0] = 1
>          a[1] = 0
>          a.dtype = np.bool
>          return a
> Will a numpy bool array be np.uint8 on all platforms?

Someone else will have to answer that for sure, though I expect and 
always assumed so.

> How can I do a.dtype=np.bool using the numpy C api? Is there any point
> (speed) in doing so?

Did you try

np.ndarray[np.uint8_t, ndim=1, cast=True] a

? You should be able to do that and then pass NPY_BOOL to PyArray_EMPTY, 
to avoid having to change the dtype later.


More information about the NumPy-Discussion mailing list