我有一个文本文件,其中有来自连接到树莓派的传感器的近50k行数据。它看起来像这样:
2014-07-16 15:57:35.536579, 128, 251, 254, 255, 30.062
2014-07-16 15:57:37.763030, 132, 252, 250, 255, 30.062
2014-07-16 15:57:39.993090, 135, 249, 239, 255, 30.125
2014-07-16 15:57:42.224499, 142, 251, 221, 255, 30.125
2014-07-16 15:57:44.452908, 152, 252, 199, 255, 30.187
2014-07-16 15:57:46.683009, 162, 246, 189, 255, 30.187
所以基本上(从左到右)日期和时间,传感器1,传感器2,传感器3,传感器4,传感器5.我想通过使用Python来绘制这个,我已经阅读了matplotlib用于绘制图形。但是如何从文本文件中绘制这些数据呢?我想在x轴上绘制时间戳,在y轴上绘制来自一个图表中不同传感器的数据。我根本没有matplotlib经验。
为了阅读文本文件,我想到了这样的事情:
line = file.readlines()
new_line = line.strip(", ")
date = new_line[0]
sensor1 = new_line[1]
#and so on
答案 0 :(得分:2)
我建议使用pandas(类似于R)。将您的输入样本包含在文件' data.csv':
中import pandas as pd
df = pd.read_csv('data.csv', parse_dates=True,index_col=0,
names = ['timestamp','x','y','z','w','k'])
df.plot()
答案 1 :(得分:1)
如果您不想安装pandas
,那么“纯NumPy”解决方案就是使用`
import numpy as np
import datetime
# date field conversion function
dateconv = lambda s: datetime.strptime(s, '%Y-%M-%D %H:%M:%S:.%f')
col_names = ["Timestamp", "val1", "val2", "val3", "val4", "val5"]
dtypes = ["object", "uint8", "uint8", "uint8", "uint8", "float"]
mydata = np.genfromtxt("myfile.csv", delimiter=',', names=col_names, dtype=dtypes, converters={"Time": dateconv})
之后mydata
:
array([('2014-07-16 15:57:35.536579', 128, 251, 254, 255, 30.062),
('2014-07-16 15:57:37.763030', 132, 252, 250, 255, 30.062),
('2014-07-16 15:57:39.993090', 135, 249, 239, 255, 30.125),
('2014-07-16 15:57:42.224499', 142, 251, 221, 255, 30.125),
('2014-07-16 15:57:44.452908', 152, 252, 199, 255, 30.187),
('2014-07-16 15:57:46.683009', 162, 246, 189, 255, 30.187)],
dtype=[('Timestamp', 'O'), ('val1', 'u1'), ('val2', 'u1'), ('val3', 'u1'), ('val4', 'u1'), ('val5', '<f8')])
现在您可以尝试,例如mydata['val5']
:
array([ 30.062, 30.062, 30.125, 30.125, 30.187, 30.187])
datetime.datetime
对象现在存储为对象。其他所有内容都以您指定的数据类型存储。