I'm trying to work with 2d arrays that can be accessed by column names using python.
The data come from a database and it may have different types and null values.
NoneType
is not allowed in the tuples so I tried to replace them by np.nan.
This piece of code works if there are no null values in the database. However, my final goal is to have a masked array, but I cannot even create an array.
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)
The resulting error is:
x = numpy.array(results, dtype=dtypes)
ValueError: cannot convert float NaN to integer
After performing fetchall, results contain something like:
[(10L,
'*',
Decimal('3.47'),
180L),
(27L,
' ',
Decimal('7.21'),
None)]
Any idea of how can I solve this problem? Thank you!