Numba中namedtuple与ListType配合出现NotImplementedError问题
解决Numba中NamedTuple与ListType结合的NotImplementedError异常
问题根源
你的代码中TransNoteType的类型定义与实际传入的参数类型不匹配:
TransNoteType里第四个字段buy_pos被定义为nb.float64,但调用append_tn时传入的buy_pos是整数100,导致生成的TransNote实例该字段实际类型为int64。Numba在尝试将这个类型不匹配的元组转换为预定义的NamedTuple类型时,触发了tuple_to_tuple的NotImplementedError。- 对比
StockRec,其类型定义中buy_pos为nb.int64,与传入的整数参数类型完全匹配,因此没有异常。
修复方案
方案1:修正NamedTuple类型定义
将TransNoteType中buy_pos的类型改为nb.int64,与实际传入的参数类型对齐:
TransNoteType = nb.types.NamedTuple([nb.int64, nb.int64, nb.float64, nb.int64, nb.float64, nb.int64, nb.float64, nb.float64], TransNote)
方案2:转换参数类型以匹配定义
在创建TransNote实例时,将buy_pos转换为浮点类型,匹配TransNoteType的定义:
def append_tn(self, sym_id, buy_date, buy_price, buy_pos, buy_costs, sell_date, sell_price, sell_income): # 将buy_pos转为float类型 item = TransNote(sym_id, buy_date, buy_price, float(buy_pos), buy_costs, sell_date, sell_price, sell_income) self.tn_list.append(item)
验证效果
采用任意一种方案修改后,运行测试代码,append_tn和append_rec都能正常执行,不会抛出异常,tn_list和stock_ls均可正常存储对应的NamedTuple实例。
内容的提问来源于stack exchange,提问作者Joseph Cen
相关产品推荐
相关产品推荐

