【问题标题】:Get average value of each key in json python获取json python中每个键的平均值
【发布时间】:2021-02-25 23:20:04
【问题描述】:

假设我有一个这样的 json 数组:

[{'Time':'09:30', 'Price':'5.49'}, {'Time':'09:31', 'Price':'5.59'}, {'Time':'09:32', 'Price':'5.39'}, {'Time':'09:30', 'Price':'8.49'}, {'Time':'09:31', 'Price':'7.49'}, {'Time':'09:32', 'Price':'10.49'}]

如何创建一个新的 json 数组,其中 json 不包含重复的时间,以及同一键中每个价格的平均值?

这就是我所说的:

[{'Time':'09:30', 'Price':'6.99'}, {'Time':'09:31', 'Price':'6.54'}, {'Time':'09:32', 'Price':'7.94'}]

这是我迄今为止尝试过的:

def stack_overflow(self, json_price_action):
    average = []
    for i, json in enumerate(json_price_action):
        average.append({
            'Time': json['Time'],
            'Price': json['Price'],
            'Count': 0
        })
        for index, avg_json in enumerate(average):
            
            if average[index]['Time'] == json['Time']:
                average[index]['Price'] += json['Price']
                average[index]['Count'] += 1
            
    print(average)

我尝试制作一个计数器,以便将每个时间段的总和除以计数器。但是,我得到重复的时间值。

【问题讨论】:

  • 您是否尝试过自己解决问题?
  • 是的,如果 key:value 不存在,我尝试遍历原始 json 并附加数据,但我失败并询问堆栈溢出。
  • 你有代码吗?
  • @SuperStormer 已发布

标签: python json loops


【解决方案1】:

您可以使用defaultdict 获取所有值,同时确保没有重复项并使用 dict 理解对所有值进行平均。

from collections import defaultdict
from statistics import mean

data = [
    {"Time": "09:30", "Price": "5.49"},
    {"Time": "09:31", "Price": "5.59"},
    {"Time": "09:32", "Price": "5.39"},
    {"Time": "09:30", "Price": "8.49"},
    {"Time": "09:31", "Price": "7.49"},
    {"Time": "09:32", "Price": "10.49"},
]

res = defaultdict(list)
for i in data:
    res[i["Time"]].append(float(i["Price"]))

res = {k: mean(v) for k, v in res.items()}

print(res)
# {'09:30': 6.99, '09:31': 6.54, '09:32': 7.9399999999999995}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-28
    相关资源
    最近更新 更多