I have a numpy boolean array:
myarr = np.array([[False, True], [True, False]])
If I try to initialise a Cython MemoryView with it, like this:
cdef bint[:,:] mymem = myarr
I get this error:
ValueError: Does not understand character buffer dtype format string ('?')
If I do this instead, it works fine:
cdef np.int_t[:,:] mymem = np.int_(myarr)
How can I store a boolean numpy array using Cython MemoryViews?
I ran into the same problem some time ago. Unfortunately I did not find a direct solution to this. But there is another approach: Since an array of boolean vales has the same data type size as uint8
, you could use a memory view with this type as well. Values in the uint8
memory view can also be compared to boolean values, so the behavior is mostly equal to an actual bint
memory view:
cimport cython
cimport numpy as np
import numpy as np
ctypedef np.uint8_t uint8
cdef int i
cdef np.ndarray array = np.array([True,False,True,True,False], dtype=bool)
cdef uint8[:] view = np.frombuffer(array, dtype=np.uint8)
for i in range(view.shape[0]):
if view[i] == True:
print(i)
Output:
0
2
3