I'm trying to use dataframe to transform data:
Column 1 | Column 2 | Column 3 | Column 4
--------------------------------
A | B | 1 | #
A | B | 2 | $
A | C | 1 | %
into
Column 1 | Column 2 | Column 5
--------------------------------
A | B | [Column 3: 1, Column 4:#, Column 3:2, Column 4:$]
A | C | [Column 3: 1, Column 4:%]
Can someone please help?
Here's something pretty close (your example output is not valid python, unless it is just a string):
In []:
(df.groupby(['Column 1', 'Column 2'])[['Column 3', 'Column 4']]
.apply(lambda x: x.to_dict(orient='record'))
.reset_index(name='Column 5'))
Out[]:
Column 1 Column 2 Column 5
0 A B [{'Column 3': 1, 'Column4': '#'}, {'Column 3': 2, 'Column 4': '$'}]
1 A C [{'Column 3': 1, 'Column 4': '%'}]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.