[英]Get average value of each key in json python
Suppose I have a json array like this:假设我有一个像这样的 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'}]
How would I create a new json array where the json contains no duplicates of time, and an average of each price within the same key?我将如何创建一个新的 json 数组,其中 json 不包含重复的时间,以及同一密钥中每个价格的平均值?
Something like this is what I am talking about:我正在谈论的是这样的事情:
[{'Time':'09:30', 'Price':'6.99'}, {'Time':'09:31', 'Price':'6.54'}, {'Time':'09:32', 'Price':'7.94'}]
This is what i have tries so far:这是我到目前为止所尝试的:
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)
I tried to make a counter so I can divide the sum of each timefram by counter.我试着做一个计数器,这样我就可以将每个时间段的总和除以计数器。 However, I get duplicate time values.
但是,我得到重复的时间值。
You can use a defaultdict
to grab all the values while making sure not to have duplicates and average out all values with a dict comprehension.您可以使用
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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.