我有一个数据帧,我想按GROUP BY并将列的字符串连接在一起.所以类似于下面的内容.

df = pd.DataFrame({
    'id': [1, 1, 2, 2, 3, 3], 
    'txt': ['sth', 'sth else', 'sth', 'one more thing', 'sth else', 'sth else'],
    'status': ['open', 'open', 'closed', 'open', 'open', 'open']})

df.assign(output=
    df.where(df.status=='open')
      .groupby(df.id)
      .txt.transform(lambda col: ', '.join(col.fillna(''))))

这给了我这个

   id   txt             status  output
0   1   sth             open    sth, sth else
1   1   sth else        open    sth, sth else
2   2   sth             closed  , one more thing
3   2   one more thing  open    , one more thing
4   3   sth else        open    sth else, sth else
5   3   sth else        open    sth else, sth else

有没有办法

  1. 没有重复的值(如第4行和第5行)
  2. 如果状态为"已关闭",则不使用前导逗号(如第2行和第3行) 这样我就能得到
   id   txt             status  output
0   1   sth             open    sth, sth else
1   1   sth else        open    sth, sth else
2   2   sth             closed  one more thing
3   2   one more thing  open    one more thing
4   3   sth else        open    sth else
5   3   sth else        open    sth else

推荐答案

dropna代替fillna,并与drop_duplicates组合使用:

df.assign(output=
    df.where(df['status'].eq('open'))
      .groupby(df['id'])['txt']
      .transform(lambda col: ', '.join(col.dropna().drop_duplicates()))
         )

输出:

   id             txt  status          output
0   1             sth    open   sth, sth else
1   1        sth else    open   sth, sth else
2   2             sth  closed  one more thing
3   2  one more thing    open  one more thing
4   3        sth else    open        sth else
5   3        sth else    open        sth else

Python相关问答推荐

自定义新元未更新参数

使用polars .滤镜进行切片速度比pandas .loc慢

Python中使用时区感知日期时间对象进行时间算术的Incredit

通过优化空间在Python中的饼图中添加标签

由于NEP 50,向uint 8添加-256的代码是否会在numpy 2中失败?

标题:如何在Python中使用嵌套饼图可视化分层数据?

未删除映射表的行

Julia CSV for Python中的等效性Pandas index_col参数

numpy卷积与有效

Python—从np.array中 Select 复杂的列子集

在pandas中使用group_by,但有条件

什么是最好的方法来切割一个相框到一个面具的第一个实例?

从嵌套的yaml创建一个嵌套字符串,后面跟着点

无法连接到Keycloat服务器

基于Scipy插值法的三次样条系数

pandas:在操作pandora之后将pandora列转换为int

使用Python TCP套接字发送整数并使用C#接收—接收正确数据时出错

如何在Python中将超链接添加到PDF中每个页面的顶部?

有没有办法在不先将文件写入内存的情况下做到这一点?

SpaCy:Regex模式在基于规则的匹配器中不起作用