Python 计算 JSON 序列中键的平均值

Python compute average value of key in series of JSON

我有一个 pandas.core.series.Series,其中每个元素都是一个 JSON,如图所示

0     {"count": 157065, "grp": {"a1": 12, "a2": 32}}
1     {"count": 2342, "grp": {"a1": 4, "a2": 34}}
2     {"count": 543, "grp": {"a1": 1, "a2": 11}}
3     {"count": 156, "grp": {"a1": 56, "a2": 75}}

如何计算所有JSON中count的平均值以及a1a2的平均值?

我不完全确定这是否是您所要求的。

这是为了计算“计数”的平均值

doc1 = {"count": 157065, "grp": {"a1": 12, "a2": 32}}
doc2 = {"count": 2342, "grp": {"a1": 4, "a2": 34}}
doc3 = {"count": 543, "grp": {"a1": 1, "a2": 11}}
doc4 = {"count": 156, "grp": {"a1": 56, "a2": 75}}
lojs = [doc1, doc2, doc3, doc4] # list of all the jsons

countaverage = 0
# For every json, it gets the count and adds it to the variable I defined
for j in lojs:
    countaverage += j["count"]
# Divides it by the length of the amount of documents
countaverage = countaverage/len(lojs)

如果你想得到 a1 的平均值,而不是上面的平均值,你可以使用这个代码:

a1average = 0
for j in lojs:
    a1average += j["grp"]["a1"] # getting "a1" inside of "grp"
a1average = a1average/len(lojs)

如果想得到 a2,你可以将 a1 换成 a2

EXTENSION 对于可能有不同数量的“a”的文档:

doc1 = {"count": 157065, "grp": {"a1": 12, "a2": 32}}
doc2 = {"count": 2342, "grp": {"a1": 4, "a2": 34}}
doc3 = {"count": 543, "grp": {"a1": 1, "a2": 11, "a3": 46, "a4": 23}}
doc4 = {"count": 156, "grp": {"a1": 56, "a2": 75, "a3": 23}}
lojs = [doc1, doc2, doc3, doc4]

grps = [] # defining a list that will contain all of the "a"s
for doc in lojs: # getting each document in the list of documents
    for a in doc["grp"].keys(): # getting all the keys in the grp of that document
        if a not in grps: # checking whether the "a" already exists in the list of "a"s
            grps.append(a) # adding the new "a" to the list

averages = {} # using a dict instead of a list because it will be containing multiple values
for grp in grps: # getting each "a"
    averages[grp] = [0, 0] # setting the value of that "a" to zero

for grp in grps: # getting each "a"
    for doc in lojs: # getting each document
        if grp in doc["grp"].keys(): # getting every "a" in the grp of the document
            averages[grp][0] += doc["grp"][grp] # adding the value of that a to the corresponding value/key (idk dude) in the dictionary
            averages[grp][1] += 1 # increasing the amount the "a" has been mentioned by 1

for el in averages: # getting each average
    averages[el][0] = averages[el][0]/averages[el][1] # dividing b

您可以使用

获得每个平均值的值

averages["a3"][0]

当然,您可以将“a3”更改为您想要的任何“a”。 顺便说一句,如果不清楚,您将获得第一个元素,因为该键的值是一个列表,其中包含平均(如果是单词则为 idk)值和“a”在您的内部出现的次数文档。

这可能不是最有效的方法,但我的意思是,它有效!