Reputation: 639
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
Upvotes: 2
Views: 864
Reputation: 862801
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)]
Upvotes: 2
Reputation: 29711
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)]
Upvotes: 2