You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

合并pandas时间戳后绘图报错:Python int too large to convert to C long

解决Matplotlib绘制时间戳时的OverflowError问题

首先看你的报错OverflowError: Python int too large to convert to C long,这是因为Matplotlib在处理你传入的时间数据时,把pandas的datetime对象转换成了纳秒级时间戳整数,这个数值太大,超出了Windows系统下C语言long类型的范围,导致转换失败。

结合你的代码和数据,给你几个针对性的解决步骤:

1. 确保时间数据类型正确

先确认所有时间序列都是datetime64[ns]类型,这是pandas和Matplotlib兼容的标准时间类型。在代码里添加检查:

print("log_time dtype:", log_time.dtype)
print("log_time_1 dtype:", df.log_time_1.dtype)
print("cm_time_4 dtype:", df.cm_time_4.dtype)

如果输出不是datetime64[ns],用pd.to_datetime重新转换:

log_time = pd.to_datetime(log_time, errors='coerce')
df['log_time_1'] = pd.to_datetime(df['log_time_1'], errors='coerce')
df['cm_time_4'] = pd.to_datetime(df['cm_time_4'], errors='coerce')

2. 转换时间为Matplotlib可识别的数值

直接传递pandas的datetime Series给plt.vlines容易触发大整数转换问题,我们可以用matplotlib.dates.date2num()把时间转换成Matplotlib内部的日期数值(以天为单位的浮点数),避免超大整数:

import matplotlib.dates as mdates

# 转换所有时间序列为Matplotlib兼容的数值
log_time_num = mdates.date2num(log_time.to_pydatetime())
log_time_1_num = mdates.date2num(df.log_time_1.to_pydatetime())
cm_time_4_num = mdates.date2num(df.cm_time_4.to_pydatetime())

# 绘制垂直线
plt.figure(figsize=(18, 4))
plt.vlines(log_time_num, 0, 1, colors="g", label="Original log time")
plt.vlines(log_time_1_num, 0.3, 0.7, colors="r", lw=2, label="Matched log time")
plt.vlines(cm_time_4_num, 0.3, 0.7, colors="b", lw=2, label="CM time")

# 添加日期格式化和标签
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))
plt.gcf().autofmt_xdate()  # 自动旋转x轴标签,避免重叠
plt.legend()
plt.show()

3. 检查时间转换逻辑(可选)

你的cm_time转换代码中:

cm_time_2 = [ref_time + pd.Timedelta(minutes=np.float(i)) for i in cm_time]

确认cm_time的数值单位确实是分钟,如果原始数据是秒的话,要改成seconds=np.float(i),不过从你提供的合并后数据来看,时间间隔是20分钟,这个转换是正确的,所以这一步可以忽略。

这样修改后,Matplotlib就能正确处理时间数据,不会再触发OverflowError了。

内容的提问来源于stack exchange,提问作者Jetman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:30:36