我从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绘图的整数列表就足以得到一个图。