python - 快速索引 : Cython with numpy array of bool and str

标签 python numpy indexing cython

我正在尝试加速 Python 脚本。我已经在纯 Python 中分析了代码并重构了很多。看来我仍然花费大量时间以如下方式访问一些 numpy 数组:

KeyArray[BoolArray[index]]

其中 KeyArray 是 ndim=2 并且包含字符串,BoolArray 是 ndim=1 并且包含 bool 并且索引是一个 int

我正在尝试学习 Cython,看看它能有多快。我写了以下不起作用的脚本:

import numpy as np
cimport numpy as np

def fastindexer(np.ndarray[np.str_t,ndim=1] KeyArray, np.ndarray [np.bool_t,ndim=2] BoolArray, np.int_t DateIndex):
    cdef np.ndarray[np.str_t,ndim=1] FArray = KeyArray[BoolArray[DateIndex]]
    return FArray

我知道 str/bool 类型在 np 数组中“按原样”不可用。我也试过转换,但我不明白应该怎么写。

欢迎大家帮忙

最佳答案

正如@Joe 所说,将单个索引语句移动到 Cython 不会给您带来速度。如果您决定将更多程序移至 Cython,则需要解决一些问题。

1) 您使用 def 而不是 cdef,这限制了您只能使用 Python 功能。
2)您使用旧的缓冲区语法。了解 memoryviews
3)切片二维数组很慢,因为每次都会创建一个新的内存 View 。也就是说,它仍然比 Python 快很多,但要获得最佳性能,您必须使用不同的方法。

这里有一些可以帮助您入门的东西。

cpdef func():
   cdef int i
   cdef bool[:] my_bool_array = np.zeros(10, dtype=bool)
   # I'm not if this next line is correct 
   cdef char[:,:] my_string_array = np.chararray((10, 10))
   cdef char answer

   for i in range(10):
       answer = my_string_array[ my_bool_array[i] ]

关于python - 快速索引 : Cython with numpy array of bool and str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32312206/

相关文章:

python - 优化Python中的广度优先搜索

python - 如何检查 python 对象是否是 numpy ndarray

python - 我遇到问题的 Tic-Tac-Toe 程序中的 IndexErrors

本例中MySql单列索引或多列索引

python - IndexError尝试在python中数值求解差分方程

python - 如何通过移除移动物体从多个图像中获取背景?

Python集合排序,为什么这么快?

python - 在 numpy 数组中查找局部最大值

python - 从终端在 Ubuntu 上安装 Numpy 1.9.2

java - 将变量分配给特定分隔符之间的文本字符串,例如。 “|” 使用Java