从字典中获取平均值的最快方法

Fastest way to get mean value from dictionary

print (data_Week) 给我:

{'2016-04-09 00:56': ['12.0', '50.7'], '2016-04-08 05:23': ['15.4', '49.8'], '2016-04-....}

值为 TemperatureHumidity 值。

我想从字典 data_Week 中获取 average 值。

我正在使用的方法有效,但它在我的 raspberry pi 上花费了很长时间...

for date,value in data_Week.items():
    temp_first_value_Week = float(value[0])
    temp_total_Week += temp_first_value_Week
    temp_length_Week += 1
    hum_first_value_Week = float(value[1])
    hum_total_Week += hum_first_value_Week
    hum_length_Week += 1
if temp_length_Week > 1:
    tempAverage_Week = temp_total_Week/temp_length_Week
    tempAverage_Week = "%.2f" % tempAverage_Week
tempAverage_Week = str(tempAverage_Week)+'\xb0C'
if hum_length_Week > 1:
    humAverage_Week = hum_total_Week/hum_length_Week
    humAverage_Week = "%.2f" % humAverage_Week
humAverage_Week = str(humAverage_Week)+'%'

每分钟都有一个字典条目,我正在尝试获取一周的平均值。 所以每天有 1440 个温度值和 1440 个湿度值.....每周有 10080 个值。 有没有一种聪明的方法来获得平均值。 上面的方法取圆周率 15 minutes

编辑: 我发现,脚本花了这么长时间,因为我遍历了不需要的字典,因为 BHawk mentioned in his .

我打算用 from John Coleman。它工作完美。 并感谢 Pandas 。也许如果当前版本会再次变慢,我会切换到它。 感谢您的帮助。

也许我遗漏了一些东西,但如果你想要的只是温度的平均值,那么应该可以使用 1 线解决方案并且应该 运行 快速:

>>> d = {'2016-04-09 00:56': ['12.0', '50.7'], '2016-04-08 05:23': ['15.4', '49.8']}
>>> sum(float(x) for x,y in d.values())/len(d)
13.7

你试过pandas了吗?我认为它可以针对您正在执行的 data/operations 这种数量和类型表现得更好。例如,我将示例数据保存在 json 文件和 运行 以下脚本中:

import pandas as pd

with open("data.json", "r") as handle:
  x = pd.read_json(handle, orient='index')

print("Data:")
print(x)
print("Description:")
print(x.describe()) # Will print a summary of each column

结果

Data:
                        0     1
2016-04-08 05:23:00  15.4  49.8
2016-04-09 00:56:00  12.0  50.7
Description:
               0          1
count   2.000000   2.000000
mean   13.700000  50.250000
std     2.404163   0.636396
min    12.000000  49.800000
25%    12.850000  50.025000
50%    13.700000  50.250000
75%    14.550000  50.475000
max    15.400000  50.700000

您不需要在每次读取值时都增加条目数。读取值时不需要强制转换为浮点数,它们已经是浮点数了。

尝试:

week_length = len(data_Week.keys())
if week_length > 1:
    tempAverage_Week = sum([x for x,y in data_Week.values()])/weekLength
    humAverage_Week = sum([y for x,y in data_Week.values()])/weekLength