5

Given this DataFrame

       r3  value
r1 r2           
1  2    3      1
   2    4      1
   3    2      1
   3    4      1
   4    2      1
   4    3      1
2  1    3      1
   1    4      1
   3    1      1
   3    4      1
   4    1      1
   4    3      1

...what's the best way to do this?

        r3     value
r1 r2           
1  2    3,4    2
   3    2,4    2
   4    2,3    2
2  1    3,4    2
   3    1,4    2
   4    1,3    2

Basically, I'm trying to condense the r3 column into a comma delimited string. The value column can be achieved a different way later on if necessary, or if it can be done through this whole process, even better.

2
  • So you want to group by (r1, r2) with r3 becoming the concatenation of all the individual r3s and value becoming the sum of all the individual values? (Your data could make this more obvious by having differing numbers of rows grouped and by using something other than 1 for some of the values). Commented Aug 7, 2014 at 15:21
  • Yes, r3 will be a concatenation. The value figure is basically a "count" column... so it would be # of rows concatenated from the r3 column. Commented Aug 7, 2014 at 15:30

1 Answer 1

5

You could use the agg function after grouping the dataframe. if df is your dataframe use this...

strJoin = lambda x:",".join(x.astype(str))     
df.groupby(level=[0,1]).agg({"r3":strJoin,"value":np.sum})
Sign up to request clarification or add additional context in comments.

1 Comment

This was perfect. Thank you. As a part time, amateur coder this would have taken me a long time. Many thanks.

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.