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

Python绘制含ISO 8601时间戳的CSV数据方法求助

绘制CSV中时间序列数据的方法

对于你的需求,我们可以通过Python的数据分析和绘图库快速实现,以下是两种适合新手的方案:

方案一:使用Pandas + Matplotlib(推荐,更简洁)

Pandas能轻松处理CSV数据和类型转换,Matplotlib负责绘图。

1. 安装依赖库

先在终端执行命令安装所需库:

pip install pandas matplotlib

2. 完整代码示例

import pandas as pd
import matplotlib.pyplot as plt

# 读取CSV文件,指定第一列的列名为'metric'(因为原文件无表头)
df = pd.read_csv('data.csv', header=None, names=['metric'])

# 拆分第一列的数值和时间戳,生成新列
df[['value', 'timestamp']] = df['metric'].str.split(', ', expand=True)

# 转换数据类型:数值转为浮点型,时间戳转为datetime类型
df['value'] = df['value'].astype(float)
df['timestamp'] = pd.to_datetime(df['timestamp'])

# 绘制时间序列折线图
plt.style.use('seaborn-v0_8')  # 设置美观的绘图风格
fig, ax = plt.subplots(figsize=(12, 6))  # 创建画布,设置尺寸

ax.plot(df['timestamp'], df['value'], linewidth=1.5, label='Metric Value')

# 添加图表元素
ax.set_title('Metric Over Time', fontsize=14)
ax.set_xlabel('Timestamp', fontsize=12)
ax.set_ylabel('Value', fontsize=12)
plt.xticks(rotation=45)  # 旋转x轴标签,避免重叠
ax.legend()
plt.tight_layout()  # 自动调整布局,防止标签被截断

plt.show()  # 显示图表

方案二:使用基础CSV模块 + Matplotlib(无需第三方数据处理库)

如果不想安装Pandas,也可以用Python自带的csv模块处理数据:

import csv
import matplotlib.pyplot as plt
from datetime import datetime

# 初始化存储数据的列表
values = []
timestamps = []

# 读取CSV文件
with open('data.csv', 'r', encoding='utf-8') as f:
    csv_reader = csv.reader(f)
    for row in csv_reader:
        # 提取第一列的内容并拆分
        metric_content = row[0]
        value_str, timestamp_str = metric_content.split(', ')
        # 转换数据类型并存入列表
        values.append(float(value_str))
        timestamps.append(datetime.fromisoformat(timestamp_str))

# 绘制图表
plt.figure(figsize=(12, 6))
plt.plot(timestamps, values, linewidth=1.5)
plt.title('Metric Over Time')
plt.xlabel('Timestamp')
plt.ylabel('Value')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

注意事项

  • 确保你的CSV文件路径正确,若文件不在当前代码目录,需填写完整路径(如C:/data/data.csv)
  • 如果数据中有异常格式的行,代码可能报错,可添加简单的异常处理(比如用try-except跳过错误行)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 07:10:12