after groupby how to add values in two rows to a list

Solutions on MaxInterview for after groupby how to add values in two rows to a list by the best coders in the world

showing results for - "after groupby how to add values in two rows to a list"
Wassim
21 Jan 2018
1In [1]: df = pd.DataFrame( {'a':['A','A','B','B','B','C'], 'b':[1,2,5,5,4,6]})
2        df
3
4Out[1]: 
5   a  b
60  A  1
71  A  2
82  B  5
93  B  5
104  B  4
115  C  6
12
13In [2]: df.groupby('a')['b'].apply(list)
14Out[2]: 
15a
16A       [1, 2]
17B    [5, 5, 4]
18C          [6]
19Name: b, dtype: object
20
21In [3]: df1 = df.groupby('a')['b'].apply(list).reset_index(name='new')
22        df1
23Out[3]: 
24   a        new
250  A     [1, 2]
261  B  [5, 5, 4]
272  C        [6]