我有一个dicts列表,如下所示。
[
{"value1": 53, "day": "Thu, 07 May 2015", "value2": 70, "type_of": "foo"},
{"value1": 17, "day": "Thu, 07 May 2015", "value2": 12, "type_of": "foo"},
{"value1": 21, "day": "Thu, 12 May 2013", "value2": 40, "type_of": "foo"}
]
现在,我正在尝试将"day"
键具有相同值的词组与"value1"
/ "value2"
键相加并离开{{1}单独。
以下是我的预期结果:
"type_of"
答案 0 :(得分:1)
任何不使用熊猫的理由? 它非常方便,让您的生活更轻松:
import pandas as pd
l1 = [{"value1": 53, "day": "Thu, 07 May 2015", "value2": 70, "type_of": "foo"},
{"value1": 17, "day": "Thu, 07 May 2015","value2": 12,"type_of" : "foo"},
{"value1": 21, "day": "Thu, 12 May 2013", "value2": 40, "type_of": "foo"}]
# Create a "table" with keys as column names and set as index the pair (day, type_of)
df1 = pd.DataFrame(l1).set_index(['day', 'type_of'])
# Here you sum values with same day and type_of. This is already what you are
# looking for
out_df = df1.groupby(level=[0, 1]).sum()
# This last bit is to convert back to dictionary, although I would suggest to
# use pandas dataframes rather than lists of dictionaries
out_dict = out_df.reset_index().to_dict(orient = 'record')
# out = [{'day': 'Thu, 07 May 2015', 'value1': 70L, 'value2': 82L},
# {'day': 'Thu, 12 May 2013', 'value1': 21L, 'value2': 40L}]
答案 1 :(得分:0)
我构建了一个类似于你需要的代码,希望它能帮助你完成任务。
android:orientation="vertical"
在最后一次迭代中,您可以为每一天的小组进行操作。
尝试编辑您的问题(您的“list_dicts”未正确写入)
答案 2 :(得分:0)
使用defaultdict的更紧凑的解决方案:
from collections import defaultdict
# data array in df
res = defaultdict (lambda : {"value1": 0, "value2": 0, "day": "", "type_of": "foo"})
for x in df:
res[x["day"]]["value1"] += x["value1"]
res[x["day"]]["value2"] += x["value2"]
res[x["day"]]["day"] = x["day"]
res[x["day"]]["type_of"] = x["type_of"]
print (res)