3

I am trying to return a groupby from a pandas df. I want the output values to be summed not merged. But the following merges the appropriate lists.

import pandas as pd

d = ({
    'Id' : [1,2,2,1],                 
    'Val' : ['A','B','B','A'],                  
    'Output' : [[1,2,3,4,5],[5,3,3,2,1],[6,7,8,9,1],[6,7,8,9,1]],                       
     })

df = pd.DataFrame(data = d)

df = df.groupby(['Id','Val']).agg({'Output':'sum'}, axis = 1)

Out:

                                Output
Id Val                                
1  A    [1, 2, 3, 4, 5, 6, 7, 8, 9, 1]
2  B    [5, 3, 3, 2, 1, 6, 7, 8, 9, 1]

Intended Output:

                                Output
Id Val                                
1  A    [7,9,11,13,6]
2  B    [11,10,11,11,2]

3 Answers 3

3

Or use a one-liner which converts to np.array:

df = df.groupby(['Id','Val']).apply(lambda x: x.Output.apply(np.array).sum())
print(df)

Output:

Id  Val
1   A        [7, 9, 11, 13, 6]
2   B      [11, 10, 11, 11, 2]
dtype: object
Sign up to request clarification or add additional context in comments.

1 Comment

@Wen-Ben Thanks, will +1 for you too.
2

You can change the list to numpy array then

df.Output=df.Output.apply(np.array)

df.groupby(['Id','Val']).Output.apply(lambda x : np.sum(x))
Out[389]: 
Id  Val
1   A        [7, 9, 11, 13, 6]
2   B      [11, 10, 11, 11, 2]
Name: Output, dtype: object

Comments

1

Another solution using using zip rather than using apply twice,

df.groupby(['Id','Val']).Output.apply(lambda x: [sum(i) for i in list(zip(*x))])

Id  Val
1   A        [7, 9, 11, 13, 6]
2   B      [11, 10, 11, 11, 2]

Comments

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.