当前位置: 代码迷 >> python >> 按ID分组类别python
  详细解决方案

按ID分组类别python

热度:30   发布时间:2023-07-16 10:07:34.0

我有一个表(数据框)如下

--------------------------
|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应保留代码列表的顺序。 任何帮助深表感谢

使用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

一种使用数据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