Python如何添加多个列表的总和 [英] Python how to add sums of multiple lists

查看:310
本文介绍了Python如何添加多个列表的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是列表列表.如何将总黑"和总色"的总和添加到一个仅使帐户ID"和帐户名称"相同的列表中?

The following is a list of lists. How do I add the sums of just "Total Black" and Total Color" into one list keeping just "Account ID" and "Account Name" the same?

[[{'Total Black': 3, 'Total Color': 2, 'Account ID': '2222', 'Account Name': 'Moe'}, 
  {'Total Black': 5, 'Total Color': 4, 'Account ID': '3333', 'Account Name': 'Larry'}, 
  {'Total Black': 9, 'Total Color': 6, 'Account ID': '4444', 'Account Name': 'Curly'}], 
 [{'Total Black': 8, 'Total Color': 4, 'Account ID': '2222', 'Account Name': 'Moe'}, 
  {'Total Black': 2, 'Total Color': 7, 'Account ID': '3333', 'Account Name': 'Larry'}, 
  {'Total Black': 11, 'Total Color': 9, 'Account ID': '4444', 'Account Name': 'Curly'}]]

因此结果将是:

[{'Total Black': 11, 'Total Color': 6, 'Account ID': '2222', 'Account Name': 
'Moe'}, {'Total Black': 7, 'Total Color': 11, 'Account ID': '3333', 'Account 
Name': 'Larry'}, {'Total Black': 20, 'Total Color': 15, 'Account ID': 4444, 
'Account Name': 'Curly'}]

推荐答案

让我们使用熊猫.

#From @C14L setup:

li = [
    [
        {'Total Black': 3, 'Total Color': 2, 'Account ID': '2222', 'Account Name': 'Moe'},
        {'Total Black': 5, 'Total Color': 4, 'Account ID': '3333', 'Account Name': 'Larry'},
        {'Total Black': 9, 'Total Color': 6, 'Account ID': '4444', 'Account Name': 'Curly'}
    ],
    [
        {'Total Black': 8, 'Total Color': 4, 'Account ID': '2222', 'Account Name': 'Moe'},
        {'Total Black': 2, 'Total Color': 7, 'Account ID': '3333', 'Account Name': 'Larry'},
        {'Total Black': 11, 'Total Color': 9, 'Account ID': '4444', 'Account Name': 'Curly'}
    ]
]

pd.concat([pd.DataFrame(li[i]) for i in range(len(li))])\
  .groupby(['Account ID','Account Name'])\
  .sum()\
  .reset_index()\
  .to_dict(orient='records')

输出:

[{'Account ID': '2222',
  'Account Name': 'Moe',
  'Total Black': 11,
  'Total Color': 6},
 {'Account ID': '3333',
  'Account Name': 'Larry',
  'Total Black': 7,
  'Total Color': 11},
 {'Account ID': '4444',
  'Account Name': 'Curly',
  'Total Black': 20,
  'Total Color': 15}]

详细信息:

首先,我们使用列表推导和pandas数据框构造函数为带有字典的列表的原始列表的每个元素构建数据框.

Details:

First we use list comprehension and the pandas dataframe constructor to build dataframes for each element of your original list of list with dictionaries.

接下来,使用pd.concat将这两个数据帧(在本例中为数据帧)放到一个组合的数据帧中.

Next, use pd.concat to put these two, in this case dataframes together into one combined dataframe.

使用groupby和sum来汇总总颜色"和总黑色"的值.

Use groupby with sum to aggregate values of Total Color and Total Black.

最后,重置index和to_dict以将组合的数据帧作为字典输出.

Lastly, reset index and to_dict to output combined dataframe as a dictionary.

这篇关于Python如何添加多个列表的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆