大家早上好!
有人可以帮我解决以下问题吗?预先感谢您!
我有一个 CSV 文件,其中包含时间戳(小时、分钟、秒、毫秒)和物体的亮度( float ),如下所示:
16,59,55,51 13.8 17,00,17,27 13.7 17,00,39,01 13.6 17,01,01,06 13.4
And here is my python script:
import matplotlib.pyplot as plt
import csv
from datetime import time
x = []
y = []
with open('calibrated.csv','r') as csvfile:
plots = csv.reader(csvfile, delimiter=' ')
for row in plots:
x.append(time(row[0]))
y.append(float(row[1]))
plt.plot(x,y, marker='o', label='brightness')
plt.gca().invert_yaxis()
plt.xlabel('time [UT]')
plt.ylabel('brightness [mag, CR]')
plt.legend()
plt.grid()
plt.show()
当我运行脚本时,我收到此类型错误:
Traceback (most recent call last): File "lightcurve.py", line 11, in x.append(time(row[0])) TypeError: an integer is required
我做错了什么?
最佳答案
发生错误是因为您将字符串传递给 datetime.time()
这需要整数
如果我们查看row[0]
,结果将是“16,59,55,51”
。因此,必须使用 row[0].split(",") 分割该字符串,这会创建一个字符串列表。该列表的内容需要使用 int()
转换为整数,然后可以传递给 datetime.time
函数。
您的代码将变为:
x = []
y = []
with open('calibrated.csv','r') as csvfile:
plots = csv.reader(csvfile, delimiter=' ')
for row in plots:
hours,minutes,seconds,milliseconds = [int(s) for s in row[0].split(",")]
x.append(time(hours,minutes,seconds,milliseconds))
y.append(float(row[1]))
plt.plot(x,y, marker='o', label='brightness')
plt.gca().invert_yaxis()
plt.xlabel('time [UT]')
plt.ylabel('brightness [mag, CR]')
plt.legend()
plt.grid()
plt.show()
这给出:
关于python - 使用 matplotlib 绘制时间 : TypeError: an integer is required,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48269859/