0
input={1:5,2:8,9:3,11:4,18:3,21:4,3:8}

and I would like to do the group by operation and perform the sum operation on

the value in those dictionary ..

like grp_1=1,2,3 ; grp_2=9,11,18 ; grp_3= 21

and output should like as below

grp_1= 21 (5+8+8 dict values)

grp_2= 10 (3+4+3 dict values)

grp_3= 4 

Please suggest us the simple way..

riteshtch
  • 8,629
  • 4
  • 25
  • 38
C-kira
  • 1
  • 1
  • Are the groups formed in any particular way? Like are they defined by some logical bins that are continuous? – ALollz Aug 27 '18 at 02:51
  • yes it is formed by the below code : a= [1,1,1,2,2,2,1,3,4,5,5,5,8,8,8,79] counted = defaultdict(int) for i,v in enumerate(a): input[v] += 1 print(input) like this.. – C-kira Aug 27 '18 at 03:05
  • To count elements in a list you can use `Counter` from `collections`: `counted = collections.Counter(a)`. You meant `counted[v]` instead of `input[v]`? – deeenes Aug 27 '18 at 03:16
  • I think what @ALollz was asking about was the nature of the _groups_ you've chosen. Does anything determine that 1,2,3 go in grp_1 and 9,11,18 go in grp_2? Is it completely arbitrary? Is is that every three distinct observed values in order form a group? Etc. – DSM Aug 27 '18 at 03:24

2 Answers2

0

From the example I guess you want to form constant size groups across the dict ordered by keys. In this case you can first sort the keys, get the values, generate chunks of the desired size and sum each of them. I could not find tool in the standard library which is able to yield chunks from a iterator, hence I use here the more_itertools module as suggested here.

import more_itertools as mit

d = {1: 5, 2: 8, 9: 3, 11: 4, 18: 3, 21: 4, 3: 8}

group_sums = list(map(
    sum,
    mit.more.chunked(
        (d[k] for k in sorted(d.keys())),
        3
    )
))
deeenes
  • 4,148
  • 5
  • 43
  • 59
0

I would do as follows:

import pandas as pd
# initial data
sr = pd.Series({1:5,2:8,9:3,11:4,18:3,21:4,3:8})
groups = [[1,2,3],[9,11,18],[21]]

# we will save the sums in this list
finalsum = []                   
for i in groups:  
    finalsum.append(sr[sr.index.isin(i)].sum())

So the sum of groups[0] would be finalsum[0] and so on.

FilippoBu
  • 100
  • 5