gpt4 book ai didi

python - 如何用python对列值求和

转载 作者:太空宇宙 更新时间:2023-11-03 12:50:34 25 4
gpt4 key购买 nike

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

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 的 HashMap 中接收结果,那就太好了。正如您可能猜到的,我不可能首先从数据库中获取求和值,因此才提出这个问题。

最佳答案

>>> 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com