如何使用python对列值求和

ddi*_*hev 3 python sum

我有一个看起来像这样的行集:

defaultdict(<type 'dict'>, 
{
   u'row1': {u'column1': 33, u'column2': 55, u'column3': 23}, 
   u'row2': {u'column1': 32, u'column2': 32, u'column3': 17}, 
   u'row3': {u'column1': 31, u'column2': 87, u'column3': 18}
})
Run Code Online (Sandbox Code Playgroud)

我希望能够轻松获得column1,column2,column3的总和.如果我可以为任意数量的列执行此操作,并在哈希映射中接收结果,那将是很好的columnName => columnSum.正如您可能猜到的那样,我不可能首先从数据库中获取求和值,因此提出问题的原因.

jam*_*lak 7

>>> from collections import defaultdict
>>> x = defaultdict(dict, 
    {
        u'row1': {u'column1': 33, u'column2': 55, u'column3': 23}, 
        u'row2': {u'column1': 32, u'column2': 32, u'column3': 17}, 
        u'row3': {u'column1': 31, u'column2': 87, u'column3': 18}
    }) 

>>> sums = defaultdict(int)
>>> for row in x.itervalues():
        for column, val in row.iteritems():
            sums[column] += val


>>> sums
defaultdict(<type 'int'>, {u'column1': 96, u'column3': 58, u'column2': 174})
Run Code Online (Sandbox Code Playgroud)

哦,更好的方式!

>>> from collections import Counter
>>> sums = Counter()
>>> for row in x.values():
        sums.update(row)


>>> sums
Counter({u'column2': 174, u'column1': 96, u'column3': 58}) 
Run Code Online (Sandbox Code Playgroud)

  • +1显示优于隐式和控制台输出. (3认同)