Sum of values in list when condition is met

how to sum values based on criteria in another column in excel
excel sum range based on cell value
sumif
sumif multiple criteria different columns
sum if two cells match
sumif multiple sum ranges
sum values based on criteria in another column with formula in excel
sumifs multiple criteria column and row

I have a python list l containing instances of the class Element:

class Element:
    def __init__(self, id, value):
        self.id = id
        self.value = value

l = [Element(1, 100), Element(1, 200), Element(2, 1), Element(3, 4), Element(3, 4)]

Now I want to sum all value members of the classes Elements if their id is equal to obtain this list:

l = [Element(1, 300), Element(2, 1), Element(3, 8)]

What is the most pythonic way to do this?

There is (almost?) nothing that itertools cannot do. Take a look at groupby:

from itertools import groupby
from operator import attrgetter


class Element:
    def __init__(self, id, value):
        self.id = id
        self.value = value
    def __repr__(self):  # kudos @mesejo
        return "Element({}, {})".format(self.id, self.value)

l = [Element(1, 100), Element(1, 200), Element(2, 1), Element(3, 4), Element(3, 4)]

l.sort(key=attrgetter('id'))  # if it is already sorted by 'id', comment-out

res = [Element(g, sum(sub.value for sub in k)) for g, k in groupby(l, key=attrgetter('id'))]

which results in:

print(res)   # [Element(1, 300), Element(2, 1), Element(3, 8)]

Sum values based on multiple conditions - Excel, The first step is to specify the location of the numbers: =SUMIFS(D2:D11, In other words, you want the formula to sum numbers in that column if they meet the conditions. That cell range is the first argument in this formula—the first piece of data that the function requires as input. To have a formula return one of two values based on a condition, use the IF function. To analyze data in a list based on criteria, such as profit margins or product types, use the database and list management functions (DCOUNT, DCOUNTA, DSUM etc.). See also this tip in French: Comment calculer la somme des cellules par critères.

One way would be to create a defaultdict that maps ids to sums of values. Then we can take those results and use them to build a new list of Elements. One way to do that is to use starmap to map the items of that dictionary to the arguments to Element

from collections import defaultdict
from itertools import starmap

class Element:
    def __init__(self, id, value):
        self.id = id
        self.value = value
    def __repr__(self):
        return "Element({}, {})".format(self.id, self.value)

l = [Element(1, 100), Element(1, 200), Element(2, 1), Element(3, 4), Element(3, 4)]

d = defaultdict(int)

for e in l:
    d[e.id] += e.value

print(list(starmap(Element, d.items())))
# [Element(1, 300), Element(2, 1), Element(3, 8)]

Python - Sum elements matching condition, This method uses the trick of adding elelement to the sum whenever the generator expression returns true. By the time list gets exhausted, summation of numbers  But when the condition is met I want it to sum 'Fees' for the previous months each time the condition is met. In the Excel above you will see Cell E4 = SUM(C2:C4) for Fund 1. So basically at each occurrence of Banked = "Y" then SUM the previous months values.

You could also get the desired result using set to get just the unique ids and sum to total the values. For example:

class Element:
    def __init__(self, id, value):
        self.id = id
        self.value = value

l = [Element(1, 100), Element(1, 200), Element(2, 1), Element(3, 4), Element(3, 4)]

ids = set(elem.id for elem in l)
totals = [Element(i, sum(elem.value for elem in l if elem.id == i)) for i in ids]
# [Element(1, 300), Element(2, 1), Element(3, 8)]

How to Use SUMIFS with Criteria Lists, Part 1: Summarizing Sales, But here's how you can return the sum for many criteria listed in a Criteria List. That is, in this formula, SUMIFS returns the sum of all values in the Amt column  Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Sum of values in list when condition is met. Ask

Excel formula: Sum if equal to one of many things, The Excel SUMIF function returns the sum of cells that meet a single condition. Criteria can be applied to dates, numbers, and text. The SUMIF function supports​  sum_range - the cells to sum if the condition is met, optional. As you see, the syntax of the Excel SUMIF function allows for one condition only. And still, we say that Excel SUMIF can be used to sum values with multiple criteria.

Excel SUMIFS and SUMIF with multiple criteria – formula examples, Source table to sum values by several conditions the same task can be fulfilled in early "SUMIFS-free" versions of Excel. Suppose, you have the orders list like shown in the screenshot  Output : The original list is : [3, 5, 1, 6, 7, 9] The number of odd elements: 5 Method #3 : Using reduce() + lamda reduce function does the task of accumulation as the sum function in the above used methods. lambda is used to perform the condition against which result needs to be checked.

How to sum cells by criteria, Use SUMIF if you need to sum values for a particular person or other criterion. Trig in the Or select a category listbox; select SUMIF in the Select a function list. 3​. The Sum_range field tells Excel which cells to add when the criteria is met for​  Assuming that you have a list of data set in range A1:B6 and you want to sum the values in one column (Column B) based on the text value in another column (Column A), how to achieve it. You need to remove duplicates values in Column a, then sum values in column B based on the unique text values in column A.

Comments
  • It's worth noting that this requires the list to be sorted by id already.