1

I have a python pandas data frame like this

col1 col2 col3  
s1   a    2  
s1   b    1  
s1   c    3  
s2   d    2  
s2   e    5  
s2   f    1  
s3   a    2 

I want to reshape it like this

col1  col2_appended col3_sum  
s1    a,b,c         6  
s2    d,e,f         8     
s3    a             2  

First column has distinct values from col1, the second column has values of col2 concatenated with commas and the 3rd column has sum of col3.

1 Answer 1

4

Use

df.groupby('col1', as_index=False).agg({'col2': ','.join, 'col3': sum})

    col1    col2    col3
0   s1      a,b,c   6
1   s2      d,e,f   8
2   s3      a       2
Sign up to request clarification or add additional context in comments.

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.