问题描述
我有一个表(数据框)如下
--------------------------
|ID | code | happened|
--------------------------
| 1 | A | 1 |
| 1 | B | 1 |
| 1 | A | 1 |
| 2 | A | 0 |
| 2 | c | 0 |
| 2 | D | 0 |
| 3 | E | 1 |
| 3 | E | 1 |
happened
不会更改ID
--------------------------
|ID | list | happened |
---------------------------
| 1 | A,B,A| 1 |
| 2 | A,C,D | 0 |
| 3 | E, E | 1 |
该list
应保留代码列表的顺序。
任何帮助深表感谢
1楼
使用agg
df.groupby('ID',as_index=False).agg({'code': lambda x : ','.join(x),'happened':'first'})
Out[911]:
ID code happened
0 1 A,B,A 1
1 2 A,c,D 0
2 3 E,E 1
2楼
一种使用数据pivot_table
的方法:
(df.pivot_table(
index='ID', values='code', aggfunc=','.join).join(df.groupby('ID').happened.first()))
code happened
ID
1 A,B,A 1
2 A,c,D 0
3 E,E 1