如何用Python转换Grafana导出CSV的延迟单位并可视化数据
处理Grafana导出CSV的延迟单位统一及可视化方案
一、将延迟统一转换为秒的Python代码
使用pandas可高效处理CSV中的单位转换,步骤如下:
- 安装依赖(未安装时执行):
pip install pandas
- 读取并处理CSV数据:
import pandas as pd # 读取CSV,适配多空格分隔符,同时解析时间列为日期类型 df = pd.read_csv('latency_data.csv', sep='\s+', parse_dates=['time'], index_col='time') # 定义单位转换函数 def convert_to_seconds(latency_entry): value, unit = latency_entry.split() numeric_value = float(value) if unit == 'ms': return numeric_value / 1000 elif unit == 's': return numeric_value raise ValueError(f"无法识别的单位: {unit}") # 应用转换,生成秒级延迟列 df['latency_sec'] = df['latency'].apply(convert_to_seconds) # 可选:删除原延迟列并保存处理后的数据 df = df.drop('latency', axis=1) df.to_csv('processed_latency_data.csv')
说明:原CSV采用多空格分隔,因此用sep='\s+'适配;解析time列为日期类型,方便后续可视化时的时间轴处理。
二、Python可视化方案
基于处理后的DataFrame,可使用matplotlib或seaborn生成直观图表:
1. 折线图(展示延迟随时间的变化趋势)
import matplotlib.pyplot as plt plt.figure(figsize=(12, 6)) df['latency_sec'].plot(kind='line', color='#1f77b4') plt.title('API延迟时间趋势(单位:秒)') plt.xlabel('时间') plt.ylabel('延迟(秒)') plt.grid(axis='y', linestyle='--') plt.xticks(rotation=45) plt.tight_layout() plt.show()
2. 柱状图(对比离散时间点的延迟差异)
plt.figure(figsize=(10, 5)) df['latency_sec'].plot(kind='bar', color='#2ca02c') plt.title('各时间点API延迟对比(单位:秒)') plt.xlabel('时间') plt.ylabel('延迟(秒)') plt.xticks(rotation=45) plt.tight_layout() plt.show()
3. 使用Seaborn生成更美观的趋势图
import seaborn as sns plt.figure(figsize=(12, 6)) sns.lineplot(data=df, x=df.index, y='latency_sec', marker='o', color='#ff7f0e') plt.title('API延迟变化趋势') plt.xlabel('时间') plt.ylabel('延迟(秒)') plt.xticks(rotation=45) plt.grid(axis='y', alpha=0.3) plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者Benjamin B
相关产品推荐
相关产品推荐

