Pythonを使用して列名でアクセスできる2次元配列を操作しようとしています。データはデータベースから取得され、さまざまな型と null 値を持つ場合があります。
NoneType
はタプルでは許可されていないため、np.nan に置き換えようとしました。
このコードは、データベースに null 値がない場合に機能します。ただし、最終的な目標はマスクされた配列を作成することですが、配列を作成することさえできません。
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)]
この問題を解決するにはどうすればよいですか?ありがとうございました!