【问题标题】:Python plotting time versus packets based on csv filePython基于csv文件绘制时间与数据包
【发布时间】:2012-05-26 08:39:50
【问题描述】:

我在这样的文本文件中有一堆数据:

99150, 2012-05-18 14:30:08.592276
100350, 2012-05-18 14:31:09.093357
97710, 2012-05-18 14:32:09.583485
94980, 2012-05-18 14:33:10.047794
95670, 2012-05-18 14:34:10.559798
97170, 2012-05-18 14:35:11.073576
98850, 2012-05-18 14:36:11.562930
98280, 2012-05-18 14:37:12.058591
97950, 2012-05-18 14:38:12.547585
102510, 2012-05-18 14:39:13.053431

我想对其进行简单的绘图并输出图像。我从以下开始:

#!/bin/python

import csv
import matplotlib.pyplot as plt
import numpy as np

filename="pps_counter.log"

def getColumn(filename, column):
    results = csv.reader(open(filename), delimiter=",")
    return [result[column] for result in results]

time = getColumn(filename,1)
packets = getColumn(filename,0)

plt.figure("Packets Per Minute")
plt.xlabel("Time(minutes)")
plt.ylabel("Number of Packets")
plt.plot(time,packets)

当我运行它时,我收到以下错误:

Traceback (most recent call last):
  File "plotter.py", line 16, in <module>
    time = getColumn(filename,1)
  File "plotter.py", line 14, in getColumn
    return [result[column] for result in results]
IndexError: list index out of range

谁能帮忙?

【问题讨论】:

    标签: python csv graph numpy matplotlib


    【解决方案1】:

    我会使用一些错误检查 喜欢

    return [ result[column] if column < len( result ) else None for result in results]
    

    您的文件中似乎有一行缺少,

    【讨论】:

    • 也可以是最后一个空行;这会导致同样的错误。
    • 我添加了@corn3lius 建议的错误检查,但我也尝试了旧方法并删除了文件中的尾随空行,两者都导致:文件“plotter.py”,第 21 行,在 plt.figure("Packets Per Minute") File "/usr/lib64/python2.7/site-packages/matplotlib/pyplot.py", line 257, in figure num = int(num) # num的粗略验证论据
    • 我使用 None (null) 对象作为错误情况,您可以使用 0 或图表中明显的内容。或者您可以找到并删除输入中的行。
    【解决方案2】:

    我建议使用csv2rec(或带有转换器功能的genfromtxt)。这会将时间转换为 python 日期时间,您可以使用 matplotlib 绘制。

    from matplotlib.mlab import csv2rec
    import matplotlib.pyplot as plt 
    
    data = csv2rec('pps_counter.log', names=['packets', 'time'])
    
    plt.plot_date(data['time'], data['packets'])
    plt.xlabel("Time(minutes)")
    plt.ylabel("Number of Packets")
    plt.title("Packets Per Minute")
    
    plt.show()
    

    【讨论】:

    • 太棒了!谢谢,我已经自定义了图表并将其设置为输出到文件...谢谢。
    猜你喜欢
    • 2017-12-12
    • 1970-01-01
    • 2020-02-13
    • 2016-05-28
    • 2021-06-28
    • 1970-01-01
    • 2020-10-17
    • 2017-11-19
    • 1970-01-01
    相关资源
    最近更新 更多