Input dataset
Var1 Var2 Var3 Var4
101 XXX yyyy 12/10/2014
101 XYZ YTRT 13/10/2014
102 TTY UUUU 9/9/2014
102 YTY IUYY 10/10/2014
Output Dataset expected:
Var1 Var2 Var3 Var4
101 XXX,XYZ yyyy,YTRI 12/10/2014, 13/10/2014
102 TTY,YTY UUUU,IUYY 9/9/2014, 10/10/2014
how can the expected dataset be achieved through pandas programming?
One way would be:
import pandas as pd
data = {'Var1': {0: 101, 1: 101, 2: 102, 3: 102},
'Var2': {0: 'XXX', 1: 'XYZ', 2: 'TTY', 3: 'YTY'},
'Var3': {0: 'yyyy', 1: 'YTRT', 2: 'UUUU', 3: 'IUYY'},
'Var4': {0: '12/10/2014', 1: '13/10/2014', 2: '9/9/2014', 3: '10/10/2014'}}
df = pd.DataFrame(data)
df.set_index('Var1', inplace=True)
print df
Var2 Var3 Var4
Var1
101 XXX yyyy 12/10/2014
101 XYZ YTRT 13/10/2014
102 TTY UUUU 9/9/2014
102 YTY IUYY 10/10/2014
f = lambda x: ','.join(x)
print df.groupby(level='Var1', as_index=True).transform(f).drop_duplicates().reset_index()
Var1 Var2 Var3 Var4
0 101 XXX,XYZ yyyy,YTRT 12/10/2014,13/10/2014
1 102 TTY,YTY UUUU,IUYY 9/9/2014,10/10/2014
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.