Cython布尔numpy数组 [英] Boolean numpy arrays with Cython

查看:132
本文介绍了Cython布尔numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy布尔数组:

I have a numpy boolean array:

myarr = np.array([[False, True], [True, False]])

如果我尝试用它初始化Cython MemoryView,如下所示:

If I try to initialise a Cython MemoryView with it, like this:

cdef bint[:,:] mymem = myarr

我收到此错误:

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)

如何使用Cython MemoryViews存储布尔型numpy数组?

How can I store a boolean numpy array using Cython MemoryViews?

推荐答案

前段时间,我遇到了同样的问题.不幸的是,我没有找到直接的解决方案.但是还有另一种方法:由于布尔值数组的数据类型大小与 uint8 相同,因此您也可以使用这种类型的内存视图.还可以将 uint8 内存视图中的值与布尔值进行比较,因此行为基本上等于实际的 bint 内存视图:

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)

输出:

0
2
3

这篇关于Cython布尔numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆