我正在编写一个python脚本,它生成一个csv文件,从文件夹中的所有csv文件读取不同的列。现在我生成文件并对列进行排序。 生成csv的代码是:
import csv
import glob
import os, sys
dirs = glob.glob('*.csv')
namelist = list(dirs)
timestamp = ['TimeStamp']
file1 = dirs[0]
for file in namelist:
namelist[namelist.index(file)] = file.partition("TrendLogExtended_")[2].partition("-Ext).csv")[0]
primariga=[]
primariga.extend(timestamp)
primariga.extend(namelist)
print dirs[0]
print len(dirs)
print namelist[0]
primofile = csv.reader(open(file1, 'rb'), delimiter=";", quotechar='|')
output_rows = []
for row in primofile:
output_rows.append([row[2]])
for file in dirs:
data = csv.reader(open(file, 'rb'), delimiter=";", quotechar='|')
column = []
for idx,row in enumerate(data):
output_rows[idx].append(row[15])
with open("provaoutput.tmp", 'wb') as f:
writer = csv.writer(f, delimiter=';')
for row in output_rows:
writer.writerow(row)
with open("provaoutput.tmp", 'r') as data_file:
lines = data_file.readlines()
lines[0]= ";".join(primariga) +"\n"
with open("finale.txt", 'w') as out_data:
for line in lines:
out_data.write(line)
通过这个脚本,我生成了一个CSV,它看起来像:
^{pr2}$我用另一个脚本对这个csv进行排序,如下所示:
import numpy as np
a = np.loadtxt('finale.txt', dtype=str, delimiter=';')
s = a[0].argsort() # produces the indexes which would sort the header
s = np.append(0, s[s!=0]) # put 0 at the front again, that's Timestamp
final = a[:,s]
np.savetxt('finale-2.txt', final, fmt='%s', delimiter=';')
我得到:
TimeStamp;AM;RHNoEB;TH
2014/08/27 11:15:19.658;;;
2014/08/27 10:15:26.060;24.51;19.23;52.51
2014/08/27 10:15:56.050;24.24;19.18;52.51
2014/08/27 10:16:26.060;24.89;19.45;52.48
2014/08/27 10:16:56.045;25.16;19.83;52.37
....
到目前为止还不错。现在我有两个问题。有些行(如第二行)只有时间戳,没有任何度量。我想删除所有这些“空”行(我的意思是)。我该怎么做?在
第二个问题是,我想生成另一个csv,计算每5或10行(X分钟)的平均值。我的意思是:
TimeStamp;AM;RHNoEB;TH
2014/08/27 10:15;24.375;19.205;52.51
2014/08/27 10:16;25.025;19.64;52.425
....
时间戳不是个大问题,我可以使用第一个度量的时间戳来计算平均值。 你能帮帮我吗?在
更多关于平均值的信息。在
每一行我都有不同设备的测量值。 我想计算每个设备的平均每X个度量值(X行)(每列,每个设备都有自己的列)。X可以是每10行,或者类似的。 输入csv是我用前面的脚本排序和清理的那个。在
我的意思是:
timestamp1-1;5;4;2
timestamp1-2;3;6;4
timestamp2-1;4;2;1
timestamp2-2;8;4;1
并获得
timestamp1-1;4;5;3
timestamp2-1;6;3;1
要消除无效的时间戳,可以使用以下示例:
这段代码从一个文件中复制所有不以“;”结尾的行,并将它们复制到另一个文件中。如果这个条件不足以满足您的需求,您应该考虑使用正则表达式。在
编辑:添加问题第二部分的答案
关于每X行每列的平均值,该代码应该起作用:
data=[“时间1-1;5;4;2”, “时间1-2;3;6;4”, “时间2-1;4;2;1”, “时间2-2;8;4;1”]
^{pr2}$我使用了一个小的子函数使它更具可读性。在
希望有帮助。在
这应该计算平均值,忽略没有测量值的线
p.S未测试
相关问题 更多 >
编程相关推荐