【发布时间】:2017-12-26 13:45:20
【问题描述】:
我已从 SQL 数据库表中提取数据,但在尝试在两个变量之间绘制图形时一直遇到问题。这是由于数据类型之间的转换问题。我首先成功地将list 转换为str 数据类型,现在我想将其转换为float/int/decimal 类型,以便可以将它与matplotlib 一起使用。我现在感觉卡住了,因为我无法将str 数据转换为其中的任何一个。下面显示的是我的脚本:
import mysql.connector as mariadb
import matplotlib as mpl
mpl.use('Agg')
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
from matplotlib import pyplot
from decimal import Decimal
import pandas as pd
mariadb_connection = mariadb.connect(user='user', password='password', database='mydatabase')
cur = mariadb_connection.cursor()
cur.execute("SELECT time, current FROM table1")
current = []
time = []
for row in cur.fetchall():
current.append(int(row[1]))
time.append(str(row[0]))
print(type(time)) #at this point terminal shows it is a list data type
time = pd.to_datetime(time)
print(type(time)) #at this point terminal shows it is a <class 'pandas.core.indexes.datetimes.DatetimeIndex'>data type
print(type(current)) #at this point, terminal shows it is a list data type
current=','.join(str(v) for v in current)
print(type(current)) #at this point, terminal shows it is a str data
current=float(current) #at this point, I get an error stating ValueError: invalid literal for float()
print(type(current))
mariadb_connection.close()
plt.figure()
plt.plot(time, current)
plt.show()
fig.savefig('plot.jpg')
在运行此脚本时,我收到一条错误消息,指出
ValueError: invalid literal for float(): 51,52,52,53,52,52,53,53,55,54,58,72,63,68,79,140,133,102,116,120,189,196,151,249,277,218,206,210,212,173,194,216,181,166,221,212,175,189,288,300,281,210,266
然后我将current=float(current) 行修改为current=int(current) 以尝试将str 数据转换为int 类型,它指出另一个错误ValueError: invalid literal for int() with base 10: '51,52,52,53,.....
然后我还尝试通过将该行更改为current=decimal(current) 将我当前的变量转换为十进制类型,但我得到decimal.InvalidOperation: Invalid literal for Decimal: '51,52,52....
关于如何将我的 current 值转换为 int/float/decimal 类型的任何建议?
更新:无需执行当前变量的转换步骤。显然,仅使用带有 pandas 绘图的整数列表就足以获得绘图。
【问题讨论】:
-
使用
,字符分割字符串,并将每个数字转换为 int。现在,你正试图告诉机器“嘿,我有一个字符串,我希望它是一个整数。你能告诉我哪个整数 '51,52,52,53,52(...)' 是?”。不。你必须把你的句子分成所有分离的数字。然后,你会告诉机器:“嘿,我得到了一个数字列表,但它们是字符串的形式。你能把它们转换成实际的数字吗?”。 -
您在
for循环中将current作为整数列表,然后将其转换为字符串,然后您需要浮点数列表...不需要。使用你原来的整数列表 -
@joaquin。我想你指的是这条线?
current.append(int(row[1])。虽然我申请了int(),但我从中得到的数据类型仍然是一个列表。因此,我仍然不能用它来绘制我的图表。 -
是的,是一个(整数)列表。应该适用于情节
-
@IMCoins。谢谢你的建议。我尝试了这种方法并将有问题的行更改为
re.split(r",", current)。数据类型现在是str。然后我将 int() 应用于此,但得到了通常的错误:ValueError: invalid literal for int() with base 10: '51,52.....
标签: python mysql matplotlib int decimal