我试图使用来自 MySQL 的数据在 Python 中绘制图表,但出现以下错误:
File "mygraph.py", line 45, in <module>
Raw = numpy.fromiter(cursor.fetchall(), count=-1, dtype=[('', numpy.float)]*3)
TypeError: float() argument must be a string or a number
日期使用datetime
格式保存在数据库中。以下是我的代码的一部分:
cursor = DBconn.cursor()
sql = "select mydate,temp,hum from temptable where unix_timestamp(mydate) >= (unix_timestamp(now())-(60*60*24))"
cursor.execute(sql)
Raw = numpy.fromiter(cursor.fetchall(), count=-1, dtype=[('', numpy.float)]*3)
Raw = Raw.view(numpy.float).reshape(-1, 3)
(samples,ports)=Raw.shape
print 'Samples: {}, DataPoints: {}'.format(samples,ports),
plotme=numpy.zeros((samples,ports-1)) # make an array the same shape minus the epoch numbers
问题可能出在日期格式上,例如我保存在 datetime
中,但我使用纪元调用?谁能指导我如何解决这个问题?
更新:cursor.fetchall()
打印以下内容:
((datetime.datetime(2015, 7, 24, 21, 2, 1), Decimal('21.4'), Decimal('60.9')))
最佳答案
您在调用 np.fromiter
时指定的数据类型与 cursor.fetchall()
返回的元组列表的相应类型不匹配。每个元组中的第一项是 datetime.datetime
,但您的 dtype 由所有 float 组成。由于没有安全的方法将 datetime.datetime
转换为 float ,因此您会收到 TypeError
。
尝试创建第一个字段 numpy.datetime64
而不是 float :
numpy.fromiter(cursor.fetchall(), count=-1,
dtype=zip(('',) * 3, ('M8[us]', '<f8', '<f8'))))
关于python - 将包含日期时间对象的元组转换为 numpy 结构化数组时出现 `TypeError: float() argument must be a string or a number`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31626691/