我正在尝试使用可以通过列名称使用python访问的2d数组。数据来自数据库,并且可能具有不同的类型和空值。NoneType
在元组中不允许使用,因此我尝试用np.nan替换它们。
如果数据库中没有空值,则这段代码有效。但是,我的最终目标是拥有一个蒙版数组,但是我什至无法创建一个数组。
import MySQLdb
import numpy
connection = MySQLdb.connect(host=server, user=user, passwd=password, db=db)
cursor = connection.cursor()
cursor.execute(query)
results = list(cursor.fetchall())
dt = [('cig', int), ('u_CIG', 'S10'), ('e_ICO', float), ('VCO', int)]
for index_r, row in enumerate(results):
newrow = list(row)
for index_c, col in enumerate(newrow):
if col is None:
newrow[index_c] = numpy.nan
results[index_r] = tuple(newrow)
x = numpy.array(results, dtype=dt)
产生的错误是:
x = numpy.array(results, dtype=dtypes)
ValueError: cannot convert float NaN to integer
执行fetchall之后,结果包含以下内容:
[(10L,
'*',
Decimal('3.47'),
180L),
(27L,
' ',
Decimal('7.21'),
None)]
关于如何解决此问题的任何想法?谢谢!
以Larsmans为例,我想您想要的是:
import numpy as np
import numpy.ma as ma
values = [('<', 2, 3.5, 'as', 6), (None, None, 6.888893, 'bb', 9),
('a', 66, 77, 'sdfasdf', 45)]
nrows = len(values)
arr = ma.zeros(nrows, dtype=[('c1', 'S1'),('c2', np.int), ('c3', np.float),
('c4', 'S8'), ('c5', np.int)])
for i, row in enumerate(values):
for j, cell in enumerate(values[i]):
if values[i][j] is None:
arr.mask[i][j] = True
else:
arr.data[i][j] = cell
print arr
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句