我有一个温度数据的文本文件,如下所示:
3438012868.0 0.0 21.7 22.6 22.5 22.5 21.2
3438012875.0 0.0 21.6 22.6 22.5 22.5 21.2
3438012881.9 0.0 21.7 22.5 22.5 22.5 21.2
3438012888.9 0.0 21.6 22.6 22.5 22.5 21.2
3438012895.8 0.0 21.6 22.5 22.6 22.5 21.3
3438012902.8 0.0 21.6 22.5 22.5 22.5 21.2
3438012909.7 0.0 21.6 22.5 22.5 22.5 21.2
3438012916.6 0.0 21.6 22.5 22.5 22.5 21.2
3438012923.6 0.0 21.6 22.6 22.5 22.5 21.2
3438012930.5 0.0 21.6 22.5 22.5 22.5 21.2
3438012937.5 0.0 21.7 22.5 22.5 22.5 21.2
3438012944.5 0.0 21.6 22.5 22.5 22.5 21.3
3438012951.4 0.0 21.6 22.5 22.5 22.5 21.2
3438012958.4 0.0 21.6 22.5 22.5 22.5 21.3
3438012965.3 0.0 21.6 22.6 22.5 22.5 21.2
3438012972.3 0.0 21.6 22.5 22.5 22.5 21.3
3438012979.2 0.0 21.6 22.6 22.5 22.5 21.2
3438012986.1 0.0 21.6 22.5 22.5 22.5 21.3
3438012993.1 0.0 21.6 22.5 22.6 22.5 21.2
3438013000.0 0.0 21.6 0.0 22.5 22.5 21.3
3438013006.9 0.0 21.6 22.6 22.5 22.5 21.2
3438013014.4 0.0 21.6 22.5 22.5 22.5 21.3
3438013021.9 0.0 21.6 22.5 22.5 22.5 21.3
3438013029.9 0.0 21.6 22.5 22.5 22.5 21.2
3438013036.9 0.0 21.6 22.6 22.5 22.5 21.2
3438013044.6 0.0 21.6 22.5 22.5 22.5 21.2
但是整个文件要长得多,这是前几行。第一列是时间戳,接下来的6列是温度记录。我需要编写一个循环,它将找到6个测量值的平均值,但会忽略0.0的测量值,因为这只意味着传感器没有打开。在测量的后期,第一列确实有测量。有没有办法让我写一个if语句或其他方法来只找到列表中非零数字的平均值?现在,我有:
time = []
t1 = []
t2 = []
t3 = []
t4 = []
t5 = []
t6 = []
newdate = []
temps = open('file_path','r')
sepfile = temps.read().replace('\n','').split('\r')
temps.close()
for plotpair in sepfile:
data = plotpair.split('\t')
time.append(float(data[0]))
t1.append(float(data[1]))
t2.append(float(data[2]))
t3.append(float(data[3]))
t4.append(float(data[4]))
t5.append(float(data[5]))
t6.append(float(data[6]))
for data_seconds in time:
date = datetime(1904,1,1,5,26,02)
delta = timedelta(seconds=data_seconds)
newdate.append(date+delta)
for datapoint in t2,t3,t4,t5,t6:
temperatures = np.array([t2,t3,t4,t5,t6]).mean(0).tolist()
仅查找最近5次测量的平均值。我希望找到一个更好的方法,它会忽略0.0并且当它是非0时包含第一列。
答案 0 :(得分:15)
之前的问题表明您已安装NumPy。因此,使用NumPy,您可以将零设置为NaN,然后调用np.nanmean
取平均值,忽略NaN:
import numpy as np
data = np.genfromtxt('data')
data[data == 0] = np.nan
means = np.nanmean(data[:, 1:], axis=1)
产量
array([ 22.1 , 22.08 , 22.08 , 22.08 , 22.1 , 22.06 , 22.06 ,
22.06 , 22.08 , 22.06 , 22.08 , 22.08 , 22.06 , 22.08 ,
22.08 , 22.08 , 22.08 , 22.08 , 22.08 , 21.975, 22.08 ,
22.08 , 22.08 , 22.06 , 22.08 , 22.06 ])
答案 1 :(得分:2)
您可以使用scipy.stats.tmean
制作截断/修剪的平均值或者你可以检查float(data [X])是否等于0,然后将其附加到相应的列表
答案 2 :(得分:2)
这适用于python3
import csv
with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
outfile = csv.writer(outfile, delimiter='\t')
for time, *temps in csv.reader(infile, delimiter='\t'):
temps = [float(t) for t in temps if t!='0.0']
avg = sum(temps)/len(temps)
outfile.writerow([time, avg])
答案 3 :(得分:0)
with open('infile') as f1, with open('outfile','w') as f2:
for x in f1:
nums = [float(i) for i in x.strip().split() if i!='0.0']
avg = sum(nums[1:])/len(nums[1:])
f2.write("{}\t{}".format(nums[0],avg))