如何将起始时间与经过时间结合并使用Pandas绘制温度变化图
用Pandas DataFrame绘制温度时序图
问题背景
我有一份分号分隔的CSV文件,记录了经过时间(秒)和对应温度数据:
el_time;temp_c
0;5.974
3600;6.015
7200;6.153
已知起始时间为 20.01.2023 20:05:33,我尝试用以下代码绘图但无法正常运行:
import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('temperature.csv', sep=';') start_date ='2023-01-20T20:05:33' start_date_object = datetime.strptime(start_date, '%Y-%m-%dT%H:%M:%S') x = start_date_object + df['el_time'].values y = df['temp_c'].values plt.plot(x, y)
问题分析
你的代码存在两个核心问题:
- 未导入
datetime模块,直接调用datetime.strptime会触发名称错误 df['el_time'].values是NumPy数组,无法直接与Python原生datetime对象相加,需要转换为时间增量类型
修正后的完整代码
import pandas as pd import matplotlib.pyplot as plt from datetime import datetime # 读取CSV数据 df = pd.read_csv('temperature.csv', sep=';') # 将起始时间字符串转换为datetime对象 start_time_str = '20.01.2023 20:05:33' start_datetime = datetime.strptime(start_time_str, '%d.%m.%Y %H:%M:%S') # 计算实际时间戳:起始时间 + 经过秒数转换的时间增量 df['actual_time'] = start_datetime + pd.to_timedelta(df['el_time'], unit='s') # 绘制温度时序图 plt.figure(figsize=(10, 6)) plt.plot(df['actual_time'], df['temp_c'], marker='o', linestyle='-', color='#1f77b4') plt.xlabel('时间') plt.ylabel('温度(℃)') plt.title('温度随时间变化趋势') plt.xticks(rotation=45) # 旋转x轴标签避免重叠 plt.tight_layout() # 自动调整布局 plt.show()
关键说明
- 使用
pd.to_timedelta将秒数转换为Pandas可识别的时间增量,解决了原生datetime与NumPy数组的运算冲突 - 新增
actual_time列存储计算后的实际时间,既方便绘图,也便于后续的数据筛选、分析 - 添加了图表修饰(标记点、颜色、标签旋转),提升可视化效果
内容的提问来源于stack exchange,提问作者fred
相关产品推荐
相关产品推荐

