0

This is the structure of my dataframe-

Key1 Key2 Value1 Value2
A    Alpha 16    12345
B    Beta  12    123
A    Alpha 15    1456
A    Beta  14    12345

I have to club Value 1 and Value 2 basis of unique combination of Key 1 and Key 2. I want my final table as follows:

Key1 Key2  Value1    Value2
A    Alpha {16,15}   {12345,1456}
B    Beta  {12}      {123}
A    Beta  {14}      {12345}

Kindly suggest a code. Thanks much appreciated. Coding level- 8 days old.

1 Answer 1

1

You must write your own custom aggregation function. agg gets passed every series that is not a grouping column and returns a single value. Here we use set as the aggregator.

df.groupby(['Key1', 'Key2']).agg(lambda x: set(x.values))

  Key1   Key2    Value1         Value2
0    A  Alpha  {16, 15}  {1456, 12345}
1    A   Beta      {14}        {12345}
2    B   Beta      {12}          {123}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this had worked. Couldn't vote (no reputation it seems)

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.