如何用python对列值求和

如何用python对列值求和

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

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}
})

我希望能够轻松获得 column1、column2、column3 的总和。如果我可以对任意数量的列执行此操作,并在看起来像 columnName => columnSum 的哈希映射中接收结果,那就太好了。正如您可能猜到的,我不可能首先从数据库中获取总和值,因此有理由提出这个问题。

最佳答案

>>> 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})

哦,更好的方法!
>>> 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})

关于python - 如何用python对列值求和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9903772/

10-12 16:58