每X行计算一个平均值

2 投票
4 回答
5510 浏览
提问于 2025-04-17 22:42

我正在尝试从一个文本文件中提取数据,并计算每600行的平均值。我把文件中的文本加载到一个numpy数组里,然后给它编号。我可以计算前600行的平均值,但我不太确定该怎么写一个循环,让Python为每600行计算一次平均值,并把结果写入一个新的文本文件。以下是我目前的代码:

import numpy as np

#loads file and places it in array
data = np.loadtxt('244UTZ10htz.txt', delimiter = '\t', skiprows = 2)
shape = np.shape(data)

#creates array for u wind values
for i,d in enumerate(data):
    data[i] = (d[3])
    if i == 600:
        minavg = np.mean(data[i == 600])

#finds total u mean for day
ubar = np.mean(data)

4 个回答

0

像这样的代码可以工作。虽然可能不是特别容易理解,但应该运行得比较快。

n = int(data.shape[0]/600)
interestingData = data[:,3]
daily_averages =  np.mean(interestingData[:600*n].reshape(-1, 600), axis=1)
0

下面这个程序使用了数组切片的方法来获取某一列的数据,然后通过列表推导式来计算这一列的平均值。其实,用一个for循环来做这个可能会更简单一些。

直接对数组进行切片或索引,而不是创建新的对象,这样做的好处是速度更快,因为你只是在现有数据上创建新的视图

import numpy as np

# test data
nr = 11
nc = 3
a = np.array([np.array(range(nc))+i*10 for i in range(nr)])
print a

# slice to get column
col = a[:,1]
print col

# comprehension to step through column to get means
numpermean = 2
means = [np.mean(col[i:(min(len(col), i+numpermean))]) \
         for i in range(0,len(col),numpermean)]

print means

它会打印出

[[  0   1   2]
 [ 10  11  12]
 [ 20  21  22]
 [ 30  31  32]
 [ 40  41  42]
 [ 50  51  52]
 [ 60  61  62]
 [ 70  71  72]
 [ 80  81  82]
 [ 90  91  92]
 [100 101 102]]
[  1  11  21  31  41  51  61  71  81  91 101]
[6.0, 26.0, 46.0, 66.0, 86.0, 101.0]
0

简单的解决方案是:

import numpy as np
data = np.loadtxt('244UTZ10htz.txt', delimiter = '\t', skiprows = 2)
mydata=[]; counter=0
for i,d in enumerate(data):
   mydata.append((d[3]))

    # Find the average of the previous 600 lines
   if counter == 600:
      minavg = np.mean(np.asarray(mydata))

      # reset the counter and start counting from 0
      counter=0; mydata=[]
   counter+=1
4

根据我对你问题的理解,听起来你有一个文件,想要计算每一行的平均值,直到第600行,然后重复这个过程,直到没有更多的数据。也就是说,在第600行时,你会计算第0到第600行的平均值;在第1200行时,你会计算第600到第1200行的平均值。

使用取模运算是一种方法,可以在每到第600行时计算平均值,而不需要用一个单独的变量来记录你已经循环了多少行。此外,我还使用了Numpy数组切片,来创建一个只包含数据集中第4列的原始数据视图。

这个例子应该能满足你的需求,但完全没有经过测试……我对numpy也不是特别熟悉,所以在其他回答中提到了一些更好的方法:

import numpy as np

#loads file and places it in array
data = np.loadtxt('244UTZ10htz.txt', delimiter = '\t', skiprows = 2)
shape = np.shape(data)
data_you_want = data[:,3]
daily_averages = list()


#creates array for u wind values
for i,d in enumerate(data_you_want):
    if (i % 600) == 0:
        avg_for_day = np.mean(data_you_want[i - 600:i])
        daily_averages.append(avg_for_day)

你可以修改上面的例子,把平均值写入一个新文件,而不是像我那样把它添加到一个列表中,或者直接把daily_averages列表写入你想要的任何文件。

作为额外的内容,这里有一个只使用CSV库的Python解决方案。虽然这个方案没有经过很多测试,但理论上应该能工作,而且对于刚接触Python的人来说,可能比较容易理解。

import csv 

data = list()
daily_average = list()
num_lines = 600

with open('testme.csv', 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter="\t")

    for i,row in enumerate(reader):
        if (i % num_lines) == 0 and i != 0:
            average = sum(data[i - num_lines:i]) / num_lines
            daily_average.append(average)

        data.append(int(row[3]))

希望这对你有帮助!

撰写回答