我尝试使用cython来提高循环的性能,但我正在运行 在某些问题中声明了输入的类型。
如何在我的类型化结构中包含一个字段,该字符串可以是 无论是“前线”还是“前线”。或者'返回'
我有np.recarray
,如下所示(注意长度
recarray未知为编译时间)
import numpy as np
weights = np.recarray(4, dtype=[('a', np.int64), ('b', np.str_, 5), ('c', np.float64)])
weights[0] = (0, "front", 0.5)
weights[1] = (0, "back", 0.5)
weights[2] = (1, "front", 1.0)
weights[3] = (1, "back", 0.0)
以及字符串列表和pandas.Timestamp
import pandas as pd
ts = pd.Timestamp("2015-01-01")
contracts = ["CLX16", "CLZ16"]
我正在尝试对以下循环进行cython化
def ploop(weights, contracts, timestamp):
cwts = []
for gen_num, position, weighting in weights:
if weighting != 0:
if position == "front":
cntrct_idx = gen_num
elif position == "back":
cntrct_idx = gen_num + 1
else:
raise ValueError("transition.columns must contain "
"'front' or 'back'")
cwts.append((gen_num, contracts[cntrct_idx], weighting, timestamp))
return cwts
我的尝试涉及在cython中输入weights
输入作为结构,
在文件struct_test.pyx
中,如下所示
import numpy as np
cimport numpy as np
cdef packed struct tstruct:
np.int64_t gen_num
char[5] position
np.float64_t weighting
def cloop(tstruct[:] weights_array, contracts, timestamp):
cdef tstruct weights
cdef int i
cdef int cntrct_idx
cwts = []
for k in xrange(len(weights_array)):
w = weights_array[k]
if w.weighting != 0:
if w.position == "front":
cntrct_idx = w.gen_num
elif w.position == "back":
cntrct_idx = w.gen_num + 1
else:
raise ValueError("transition.columns must contain "
"'front' or 'back'")
cwts.append((w.gen_num, contracts[cntrct_idx], w.weighting,
timestamp))
return cwts
但是我收到运行时错误,我认为这与错误相关
char[5] position
。
import pyximport
pyximport.install()
import struct_test
struct_test.cloop(weights, contracts, ts)
ValueError: Does not understand character buffer dtype format string ('w')
另外,我有点不清楚如何输入contracts
为timestamp
。
答案 0 :(得分:1)
您的ploop
(没有timestamp
变量)会产生:
In [226]: ploop(weights, contracts)
Out[226]: [(0, 'CLX16', 0.5), (0, 'CLZ16', 0.5), (1, 'CLZ16', 1.0)]
没有循环的等效函数:
def ploopless(weights, contracts):
arr_contracts = np.array(contracts) # to allow array indexing
wgts1 = weights[weights['c']!=0]
mask = wgts1['b']=='front'
wgts1['b'][mask] = arr_contracts[wgts1['a'][mask]]
mask = wgts1['b']=='back'
wgts1['b'][mask] = arr_contracts[wgts1['a'][mask]+1]
return wgts1.tolist()
In [250]: ploopless(weights, contracts)
Out[250]: [(0, 'CLX16', 0.5), (0, 'CLZ16', 0.5), (1, 'CLZ16', 1.0)]
我正在利用返回的元组列表与输入weight
数组具有相同(int,str,int)布局的事实。所以我只是复制weights
并替换b
字段的选定值。
请注意,我在mask
之前使用字段选择索引。布尔值mask
生成一个副本,因此我们必须注意索引顺序。
我猜测无环阵列版本将与cloop
(在真实数组上)及时竞争。 cloop
中的字符串和列表操作可能会限制其加速。