[英]I want to group my list of lists by date and sum the values where the dates match
I have a list of lists like that:我有一个这样的列表列表:
l = [['05-05-2015', -40], ['05-05-2015', 30], ['07-05-2015', -75], ['05-05-2015', -40], ['05-05-2015', 120], ['07-05-2015', -150]]
I want to group it by date and sum the values where the dates are equal like that:我想按日期对它进行分组并对日期相等的值求和:
[['05-05-2015', 70], ['07-05-2015', -225]]
I found this solution: python sum up list elements in list of lists based on date as unique我找到了这个解决方案: python sum up list elements in lists based on date as unique
It seems to solve my problem.它似乎解决了我的问题。 But I found the code very complex to understand and replicate in my code.
但我发现代码非常复杂,难以理解和复制到我的代码中。
Could someone explain me how I can do this?有人可以向我解释我该怎么做吗?
l = [['05-05-2015', -40], ['05-05-2015', 30], ['07-05-2015', -75], ['05-05-2015', -40], ['05-05-2015', 120], ['07-05-2015', -150]]
d = {}
for date, value in l:
d[date] = d.get(date, 0) + value
print(list(d.items()))
Output: Output:
[('05-05-2015', 70), ('07-05-2015', -225)]
This code is easier for understanding:这段代码更容易理解:
l = [['05-05-2015', -40], ['05-05-2015', 30], ['07-05-2015', -75], ['05-05-2015', -40], ['05-05-2015', 120], ['07-05-2015', -150]]
result = {}
for entry in l:
# if date is not in dictionary, adding it to dictionary, other way making summation
if entry[0] not in result:
result[entry[0]]=entry[1]
else:
result[entry[0]]+=entry[1]
print(result)
try grouped by and sum尝试分组并求和
lst = [['05-05-2015', -40], ['05-05-2015', 30], ['07-05-2015', -75], ['05-05-2015', -40], ['05-05-2015', 120], ['07-05-2015', -150]]
df=pd.DataFrame(columns=['Date','Amount'])
for item in lst:
print(item)
df=df.append({'Date':item[0],'Amount':item[1]},ignore_index=True)
df.set_index('Date',inplace=True)
grouped=df.groupby(df.index)['Amount'].sum()
res=[[item[0],item[1]] for item in grouped.items()]
print(res)
output: output:
[['05-05-2015', 70], ['07-05-2015', -225]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.