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

pandas DataFrame列转时间类型及matplotlib绘图报错解决求助

报错原因

  • 第一个报错 TypeError: float() argument must be a string or a number, not 'datetime.time' 是因为 matplotlib 的 errorbar 接口默认无法直接将 datetime.time 类型作为坐标轴输入,需要转换为其支持的时间数值格式。
  • 第二个报错 TypeError: <class 'datetime.time'> is not convertible to datetime 是因为 pd.to_datetime() 仅支持转换包含日期+时间的完整格式数据,你当前的 Sampling 列只有时间部分,没有日期信息,无法直接转换为 pandas 的 datetime 类型。

解决代码

直接替换你原来的时间转换和绘图部分即可:

#import
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import matplotlib.dates as mdates

df1 = pd.read_excel(r'results.xlsx', 'growth')
df1_sub = df1.groupby(["Sampling", ], as_index=False).agg({'NPQ':['mean', 'std']})
df1_sub.columns = ['Sampling','NPQ','std']

# 替换原来的时间转换代码:给时间补一个任意固定日期,凑成完整datetime对象
df1_sub['Sampling_datetime'] = df1_sub['Sampling'].apply(lambda x: datetime.datetime.combine(datetime.date(2024,1,1), x))
# 转成matplotlib可识别的时间数值
df1_sub['Sampling_num'] = mdates.date2num(df1_sub['Sampling_datetime'])

# 绘图代码
fig, ax1 = plt.subplots()
ax1.errorbar('Sampling_num', 'NPQ', yerr='std', data=df1_sub)
# 设置x轴仅显示时分秒,隐藏占位用的日期
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))
# 自动调整x轴标签避免重叠
fig.autofmt_xdate()
plt.show()

补充说明

如果读入的时间格式有偏差(比如Excel里14:00错误标注AM的问题),可以在读Excel时将Sampling列指定为字符串类型,再用pd.to_datetime(df1['Sampling'], format='%H:%M:%S %p')转换为时间格式,后续处理逻辑和上述代码一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:36:10