Python 使用matplotlib:TypeError打印时间:需要整数

Python 使用matplotlib:TypeError打印时间:需要整数,python,matplotlib,time,typeerror,Python,Matplotlib,Time,Typeerror,早上好 有人能帮我解决以下问题吗?提前谢谢你 我有一个CSV文件,上面有时间戳(小时、分钟、秒、毫秒)和对象的亮度(浮点),如下所示: 16,59,55,51 13.8 17,00,17,27 13.7 17,00,39,01 13.6 17,01,01,06 13.4 当我运行脚本时,我得到以下类型错误: Traceback (most recent call last): File "lightcurve.py", line 11, in x.append(time(row[0

早上好

有人能帮我解决以下问题吗?提前谢谢你

我有一个CSV文件,上面有时间戳(小时、分钟、秒、毫秒)和对象的亮度(浮点),如下所示:

16,59,55,51 13.8 17,00,17,27 13.7 17,00,39,01 13.6 17,01,01,06 13.4 当我运行脚本时,我得到以下类型错误:

Traceback (most recent call last): File "lightcurve.py", line 11, in x.append(time(row[0])) TypeError: an integer is required 回溯(最近一次呼叫最后一次): 文件“lightcurve.py”,第11行,在 x、 追加(时间(行[0])) TypeError:需要一个整数
我做错了什么?

发生错误的原因是您向需要整数的字符串传递字符串

如果我们查看
行[0]
,结果将是
“16,59,55,51”
。因此,必须使用创建字符串列表的
行[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()
其中:


您的行[0]是一个由逗号分隔的数字字符串,例如“16,59,55,51”

您需要将它们拆分为子字段,然后将每个较小的数字字符串转换为实际整数,例如:


(小时、分钟、秒、微秒)=[int(v)表示第[0]行中的v]。拆分(“,”)]
x、 追加(时间(小时、分钟、秒、微秒))

在CSV文件中扫描时,行数据在第[0]行中包含字符串。例如,csv文件的第一行变为:

row = ["16,59,55,51", "13.8"]
要解决此问题,需要将这些字符串转换为适当的值

 with open('calibrated.csv','r') as csvfile:
        plots = csv.reader(csvfile, delimiter=' ')
        for row in plots:
            t = [int(x) for x in row[0].split(',')]
            x.append(time(t[0],t[1],t[2],t[3]))
            y.append(float(row[1])
另一个选项是使用日期时间戳,如下所示:

from datetime import datetime
x = []
y = []

with open('calibrated.csv','r') as csvfile:
    plots = csv.reader(csvfile, delimiter=' ')
    for row in plots:
        x.append(datetime.strptime(row[0], '%H,%M,%S,%f'))
        y.append(float(row[1]))

这将使用毫秒作为微秒,但这对我来说似乎不是什么大问题。但是,如果需要,它允许您稍后添加日期

您需要先按空格分割
,以将时间与数据分开。然后,您需要将第一部分再次拆分为
以获得小时、分钟等。csv。reader返回str列表,time is expecting int。我已删除此问题的“更新”部分,因为您收到的关于新错误的另一个问题现已解决。否则,其他人可能会对此感到困惑David,你知道我的问题更新部分中描述的新类型错误吗?@SergiusPro您提供的示例csv数据。这正是csv采用的格式吗?是的,完全相同。嗯,您使用的是什么numpy和matplotlib版本?numpy:'1.13.3'和matplotlib:'1.5.1'
from datetime import datetime
x = []
y = []

with open('calibrated.csv','r') as csvfile:
    plots = csv.reader(csvfile, delimiter=' ')
    for row in plots:
        x.append(datetime.strptime(row[0], '%H,%M,%S,%f'))
        y.append(float(row[1]))