Marc Zaharescu Marc Zaharescu - 1 month ago 7
Python Question

Python: transform data set

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

Answer

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)]