[Numpy-discussion] Creating a bool array with Cython
Sun Feb 26 10:08:16 CST 2012
On Sat, Feb 25, 2012 at 7:04 PM, Dag Sverre Seljebotn
> 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():
>> 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 = 1
>> a = 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.
That looks like the grown up way to write the code. (Plus saves 300 ns
in overhead.) Thanks, Dag.
(I don't write the code to create the empty output array by hand. I
have a templating system that does that. But it does not know how to
create bool arrays. Hence the a.dtype = np.bool workaround. Thanks to
your advice, I'll try to teach the templating system to create bool
arrays so I don't have to remember how to do it.)
More information about the NumPy-Discussion