1

Is there a graceful way of handling None values in a conversion of a list of tuples to a numpy recarray using the single call to np.rec.fromrecords? Assuming I know what I want the missing value to be (e.g. -1 for integers), how do I catch and handle the below contrived example:

import numpy as np
a = [('Bob', 40, 3.14), ('Sue', 38, 6.28), ('Jim', None, 9.42)]
dtype = [('NAME', 'S10'), ('AGE', np.int32), ('SCORE', np.float64)]
try:
    b = np.rec.fromrecords(a, dtype=dtype)
except TypeError:
    # Convert None to 0 for AGE field here instead of raising the error
    raise TypeError('Caught a TypeError')

I'm guessing that I would have to do this on a per-field basis in order to avoid missing true TypeErrors elsewhere in the recarray. Is there any way of isolating where (ie. what fields) in the recarray I want this conversion to apply. My real use case is converting pyodbc records to numpy recarrays.

4

1 回答 1

1

使用数据库查询为 NULL 列值返回 -1,如下所示:

SELECT COALESCE(ColumnName, -1) FROM Schema.Table;

这将为 NULL 的 ColumnName 值返回 -1,否则返回实际值。如果需要,请在此处查看 COALESCE 的文档。这允许您只为您需要的列提供 NULL 替换值,并且不会屏蔽TypeError您应该关心的异常。

于 2011-08-31T14:19:01.827 回答