python - 使用 matplotlib 绘制时间 : TypeError: an integer is required

标签 python matplotlib time typeerror

大家早上好!

有人可以帮我解决以下问题吗?预先感谢您!

我有一个 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()

这给出:

enter image description here

关于python - 使用 matplotlib 绘制时间 : TypeError: an integer is required,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48269859/

相关文章:

python - 类型错误 : use() got an unexpected keyword argument 'warn' when importing matplotlib

python - 仅绘制某些日子的 Pandas 数据框

android - 如何测量移动应用程序的冷/热启动时间

java - 不同年份的两个日期之间的差异

excel - 在 Excel 中将时间格式化为天、小时、分钟和秒的更好方法?

python - if A vs if A is not None :

python - 根据具有不同索引的引用数据帧连接数据帧中的特定列对

python - 没有找到某些包的发行版

python - Brython 中的 super().__str__() 应该返回不同的东西吗?

python - 在 Python 中读取未定义数量的列并使用 matplotlib 绘制数据