使用Python从平均值大于阈值的列表中提取月度数据

时间:2014-11-26 10:57:45

标签: python python-2.7

我有两个csv文件,每个文件有两列(每天有10年的数据):

time,value
19800101,0.15
.
.
.

我使用以下内容来阅读列表ab

中的数据
import csv

a = []
with open('data.csv','rb') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        a.append([row[0],row[1]]) 

获取列表b的方法相同。我想在列表a中得到每月的平均值,如果它低于0.01,则删除属于该月的所有每日值并输出新列表。此外,我希望从列表b中删除相应的每日值,以便为其生成新列表。列表ab的长度相同,时间步长相同。 任何建议都会很有意义。

例如:

a = [0.14,1.12........] # daily values (say have 2-years = 730 values)
b = [0.11,0.005,......] # daily values (say have 2-years = 730 values)

如果列表a中的3月和4月的月平均值小于0.01,那么将会删除这些月份的每日值的以下列表:

a_new = [0.14,1.12,.....] # daily values (669 values)
b_new = [0.11,0.005,....] # daily values (669 values)

1 个答案:

答案 0 :(得分:1)

这可能不是一个非常好看且最有效的解决方案......但请告诉我它是如何工作的。

import numpy,csv

time=[]
data_a=[]
data_b=[]

#--------------------Read in a--------------------
with open('data_a.csv','rb') as csvfile:
    reader=csv.reader(csvfile)
    for row in reader:
        time.append(row[0])
        data_a.append(float(row[1]))

#--------------------Read in b--------------------
with open('data_b.csv','rb') as csvfile:
    reader=csv.reader(csvfile)
    for row in reader:
        data_b.append(float(row[1]))

data_a=numpy.array(data_a)
data_b=numpy.array(data_b)
monthly=numpy.zeros(data_a.shape)

#-----------------Get month means-----------------
for ii in xrange(len(time)):
    tt=time[ii]
    if ii==0:
        month_old=tt[4:6]
        index_start=ii
    else:
        #----------------new month----------------
        month=tt[4:6]
        if month != month_old:
            month_mean=numpy.mean(data_a[index_start:ii])
            print 'mean for month',month_old,month_mean
            monthly[index_start:ii]=month_mean
            month_old=month
            index_start=ii

    #----------------Get the last month----------------
    if ii==len(time)-1:
        month_mean=numpy.mean(data_a[index_start:])
        print 'mean for month',month_old,month_mean
        monthly[index_start:]=month_mean

#-------------------Filter data-------------------
index=numpy.where(monthly>=0.01)
data_a_filtered=numpy.take(data_a,index)
data_b_filtered=numpy.take(data_b,index)
time_filtered=numpy.take(time,index)