我想知道JSON文件的对象中包含的值的平均值。我遍历数组以检索值,然后尝试使用NumPy计算平均值
我的JSON示例:
{
"gm_url": "https://www.url.com/",
"results": [
{
"marque": "Alfa",
"sold": true
"price_int_eu": 49280
},
{
"marque": "Alfa",
"sold": true,
"price_int_eu": 46000
}
]
}
如何获取所有“ price_int_eu”的平均值并在“ gm_url”之后添加一行?
我的猜测:
for i in data:
results = i["results"]
if not results == []:
for x in results:
issold = x["sold"]
priceinteu = x["price_int_eu"]
if priceinteu is not None:
i["mean"] = np.mean(priceinteu)
print(i["mean"])
答案 0 :(得分:0)
您需要将所有价格放入一个列表(或其他类似数组的对象)中,才能使用np.mean
。
for i in data:
results = i["results"]
if not results == []:
prices = [x["price_int_eu"] for x in results]
prices = [x for x in prices if x is not None]
i["mean"] = np.mean(prices)
请注意,仅当您明确具有类似内容时,倒数第二行才有效
{
"marque": "Alfa",
"sold": false,
"price_int_eu": null
}
在您的json中。如果价格刚好丢失,则需要将x["price_int_eu"]
更改为x.get("price_int_eu")
才能使用。
编辑:要处理非空results
但没有实际价格的情况:
for i in data:
results = i["results"]
prices = [x["price_int_eu"] for x in results]
prices = [x for x in prices if x is not None]
if not prices == []:
i["mean"] = np.mean(prices)
else: i["mean"] = None