0

I have a list of lists with multi columns:

column = [id, date,col1, col2...coln]
list_OfRows = [[1,date1, 10,20 ...23],
              [1,date1, 1,10 ...33],
              [2,date2, 3,7...8],
              [2,date2, 21,9...23],
              [2,date3, 10,56 ...20],
              [2,date4, 10,20 ...42]]

I want to group by on id and date and do sum on cols WITHOUT USING PANDAS

RESULT = [[1,date1, 11,30 ...56],
         [2,date2, 24,16...31],
         [2,date3, 10,20 ...20],
         [2,date4, 10,20 ...42]]
2
  • 2
    Please always provide a minimal reproducible example and be sure to read stackoverflow.com/help/how-to-ask Commented May 31, 2021 at 11:40
  • What about mapReduce or simply use a dictionary where you collect the records by id and then apply the aggregation function. Commented May 31, 2021 at 11:46

1 Answer 1

3

You can do it like this:

from itertools import groupby


list_OfRows.sort(key=lambda x: x[:2])
res = []
for k, g in groupby(list_OfRows, key=lambda x: x[:2]):
    res.append(k + list(map(sum, zip(*[c[2:] for c in g]))))

which produces:

[[1, 'date1', 11, 30, 56], 
 [2, 'date2', 24, 16, 31], 
 [2, 'date3', 10, 56, 20], 
 [2, 'date4', 10, 20, 42]]
Sign up to request clarification or add additional context in comments.

3 Comments

Perfect usage of groupby. Very elegant solution.
@Ma0 thanks ! i this error : res.append((k + list(map(sum, zip(*[c[2:] for c in g]))))) ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() some advice?
are these numpy arrrays?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.