我使用的是pandas 0.16.2,numpy 1.9.2和numba 0.20。
有没有办法让numba在nopython模式下支持字符串数组? 或者,我可以以某种方式将字符串转换为numba会识别的数字吗?
我必须在字符串数组(来自pandas数据帧的列)上运行某些循环;如果我可以使用numba,代码会快得多。
我想出了这个最小的例子来说明我的意思:
import numpy as np
import numba
x=np.array(['some','text','this','is'])
@numba.jit(nopython=True)
def numba_str(txt):
x=0
for i in xrange(txt.size):
if txt[i]=='text':
x += 1
return x
print numba_str(x)
我得到的错误是:
Failed at nopython (nopython frontend)
Undeclared ==([char x 4], str)
谢谢!
答案 0 :(得分:9)
Numba尚不支持字符串(自20.0版起)。实际上,"character sequences are supported, but no operations are available on them"。
确实,一种可行的解决方法是将字符解释为数字。对于ASCII字符,这很简单,请参阅Python ord
和chr
函数。但是,对于您的最小示例,您最终会使用可读性较差的函数:
import numpy as np
import numba
x=np.array(['some','text','this','is'])
@numba.jit(nopython=True)
def numba_str(txt):
x=0
for i in xrange(txt.shape[0]):
if (txt[i,0]==116 and # 't'
txt[i,1]==101 and # 'e'
txt[i,2]==120 and # 'x'
txt[i,3]==116): # 't'
x += 1
return x
print numba_str(x.view(np.uint8).reshape(-1, x.itemsize))
答案 1 :(得分:3)
numba现在支持str
(从0.41版开始)