【问题标题】:Fast indexing: Cython with numpy array of bool and str快速索引:带有 bool 和 str 的 numpy 数组的 Cython
【发布时间】:2015-08-31 13:16:42
【问题描述】:

我正在尝试加快 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 thx 进行编辑。更容易阅读
  • 对于它的价值,将单个花哨的索引语句移动到 Cython 不会加快速度。它实际上已经全部是 C。与其专注于将事物转移到 Cython,有什么方法可以让您重新考虑您的数据结构?您存储数据的方式是否可以重构,使KeyArray[BoolArray[index]] 变得更像KeyArray[index]

标签: python numpy indexing cython


【解决方案1】:

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

1) 您使用 def 而不是 cdef,从而将您限制为仅限 Python 功能。
2)您使用旧的缓冲区语法。了解memoryviews
3)切片二维数组很慢,因为每次都会创建一个新的内存视图。也就是说,它仍然比 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] ]

【讨论】:

  • 你会得到'bool'不是类型标识符
猜你喜欢
  • 1970-01-01
  • 2011-11-18
  • 1970-01-01
  • 1970-01-01
  • 2018-08-10
  • 1970-01-01
  • 2014-06-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多