0

I'm struggling to make do some data wrangling on a pandas dataframe. I've been stuck on this problem for 2 days now.

I've got a dataframe that looks like this:

['a','e']
['b','f']
['c','g']
['d','h']
['a','i']
['b','j']
['c','k']
['d','l']

And I need to turn it into looking like this

['a',['e','i']]
['b',['f','j']]
['c',['g','k']]
['d',['h','l']]

So basically pivoting the original dataframe around the first column and then creating a list of strings from the second column.

thanks

1 Answer 1

3

You could use groupy/agg:

import pandas as pd

data = [['a','e'], ['b','f'], ['c','g'], ['d','h'], ['a','i'], ['b','j'], 
        ['c','k'], ['d','l']]

df = pd.DataFrame(data, columns=['first', 'second'])
print(df.groupby(['first']).agg(lambda x: x.tolist()))

yields

       second
first        
a      [e, i]
b      [f, j]
c      [g, k]
d      [h, l]
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.