简体   繁体   English

计算并返回列表中的平均值

[英]Calculate and return average values in a list

I have a long list with some values. 我列出了一些值。 I want to define a function that take the list and calculates the average for every 24 values in the list, and returns the average values as a list. 我想定义一个函数,该函数接受列表并计算列表中每24个值的平均值,然后将平均值作为列表返回。 How do I do this? 我该怎么做呢? I have 8760 elements in the list, and the list returned should give 8760/24=365 elements. 我的列表中有8760个元素,返回的列表应为8760/24 = 365个元素。

hourly_temp = ['-0.8', '-0.7', '-0.3', '-0.3', '-0.8',
'-0.5', '-0.7', '-0.6', '-0.7', '-1.2', '-1.7...] #This goes on, it's 8760 elements

def daily_mean_temp(hourly_temp):

    first_24_elements = hourly_temp[:24] #First 24 elements in the list

Is this correct? 这个对吗? I get an error saying: TypeError: cannot perform reduce with flexible type 我收到一条错误消息:TypeError:无法使用灵活类型执行归约

def daily_mean_temp(hourly_temp):
averages = [float(sum(myrange))/len(myrange) 
        for myrange in zip(*[iter(hourly_temp)]*24)]
return averages

Assuming that you want independent groups, you can use the grouper itertools recipe : 假设您想要独立的组,则可以使用grouper itertools配方

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

And then easily get the average of each group : 然后轻松获得每个group的平均值:

averages = [sum(group)/float(len(group)) for group in grouper(data, 24)]

Edit : given that your data appears to be a list of strings, I would suggest you convert to floats first using map : 编辑 :鉴于您的数据似乎是一个字符串列表,我建议您首先使用map转换为浮点数:

data = map(float, hourly_temp)
averages = [sum( map(float, myrange) )/len(myrange) 
            for myrange in zip(*[iter(my_big_list)]*range_size)]

is a pretty neat way to do it ... note that it will truncate any end variables not nicely divisible by the range size 这是一种非常整洁的方法...请注意,它将截断所有不能被范围大小整除的最终变量

if you need to have uneven lists at the end (ie chunk_size of 10 with a big_list of 17 would have 7 left over) 如果您需要在末尾添加不均匀的列表(例如,chunk_size为10,big_list为17,则剩下7个)

 from itertools import izip_longest as zip2
 averages = [sum(map(float,filter(None,myrange)))/len(filter(None,myrange)) 
            for myrange in zip2(*[iter(my_big_list)]*range_size)]

Assuming your values are strings, as you show above, and that you have NumPy handy, this should be fast: 如上所示,假设您的值是字符串,并且手边有NumPy,这应该很快:

import numpy as np
averages = [x.mean() for x in np.array_split(
        [float(x) for x in hourly_temp], 365)]

And if you might have NaNs: 如果您可能有NaN:

averages = [x[~np.isnan(x)].mean() for x in np.array_split(
        [float(x) for x in hourly_temp], 365)]

And if you start with proper floats: 如果您以正确的浮点数开始:

averages = [x[~np.isnan(x)].mean() for x in np.array_split(hourly_temp, 365)]

遵循这些思路的东西似乎可行:

[ sum(hourly_temp[i:i+24]) / len(hourly_temp[i:i+24]) for i in xrange(0, len(hourly_temp), 24) ]

Using this grouper recipe , it's pretty easy (obviously, I've synthesized the temps list): 使用这个grouper食谱 ,这很容易(显然,我已经合成了temps列表):

#!/usr/bin/python

import itertools as it

temps = range(96)

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return it.izip_longest(*args, fillvalue=fillvalue)

daily_averages = [sum(x)/len(x) for x in grouper(temps, 24)]
yearly_average = sum(daily_averages)/len(daily_averages)

print(daily_averages, yearly_average)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM