2

I have the following data set

            id  type  value
0             1   A    10
1             1   C   120
2             2   B    20
3             2   C    40
4             3   A    10
5             3   B    50

I want in python to transform it to be like (1,A,10,C,120) (2,B,20,C,40) (3,A,10,B,50)

Any suggestion would be much appreciated

2
  • 3
    Start from here, Read about this and this. Finally use this and solve your problem. As for the question it is too broad for Stack Overflow. See How to Ask and minimal reproducible example. Commented Nov 10, 2016 at 19:09
  • Also, watch this video and look at this in the pandas docs Commented Nov 10, 2016 at 19:15

2 Answers 2

2

Perform groupby w.r.t id column. Iterate over each group by converting the other two columns to a list and add the unique value corresponding to the id per group number alongside. Finally, convert them into a tuple and append these to a list.

grouped = df.groupby('id')
L = []
for _, grp in grouped:
    L.append(tuple(grouped.get_group(_)['id'].unique().tolist() + grp[['type','value']].values.ravel().tolist()))
print(L)
#[(1, 'A', 10, 'C', 120), (2, 'B', 20, 'C', 40), (3, 'A', 10, 'B', 50)]
Sign up to request clarification or add additional context in comments.

2 Comments

thanks @Nickil Maveli, however after I run your implementation after the values another 'L' is being appended, is there anyway I can get rid of it?
You mean you do not want to keep them as a list? How do you want to store them? You could also try editing the question to show what is going wrong.
2

You can use:

L = df.groupby('id').apply(lambda x: tuple([x['id'].iat[0]] + 
                                          x[['type','value']].values.flatten().tolist()))
                    .tolist()
print (L)
[(1, 'A', 10, 'C', 120), (2, 'B', 20, 'C', 40), (3, 'A', 10, 'B', 50)]

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.