【问题标题】:How to remove duplicate strings after grouping?分组后如何去除重复的字符串?
【发布时间】:2023-02-09 11:28:05
【问题描述】:

我想按 ID 列对以下 Pandas DataFrame 进行分组:


|----+----------------------------------------+-----------------|
| ID | Elements                               | Colors          |
|----+----------------------------------------+-----------------|
| A  | '1st element, 2d element, 3d element'  | 'red, blue'     |
| A  | '2d element, 4th element'              | 'blue, green'   |
| B  | '3d element, 5th element, 6th element' | 'white, purple' |
| B  | '3d element, 5th element, 7th element' | 'white, teal'   |
| B  | '3d element, 5th element, 8th element' | 'white, black'  |
|----+----------------------------------------+-----------------|

为了获得以下 Pandas DataFrame:

|----+-----------------------------------------------------------------+------------------------------|
| ID | Elements                                                        | Colors                       |
|----+-----------------------------------------------------------------+------------------------------|
| A  | '1st element, 2d element, 3d element, 4th element'              | 'red, blue, green'           |
| B  | '3d element, 5h element, 6th element, 7th element, 8th element' | 'white, purple, teal, black' |
|----+-----------------------------------------------------------------+------------------------------|

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    要在按“ID”列分组后删除“元素”和“颜色”列中的重复项,可以使用 set 函数。

    试试这个代码:

    grouped_df = df.groupby('ID').agg({'Elements': lambda x: ', '.join(list(set(', '.join(x).split(', ')))),
                                       'Colors': lambda x: ', '.join(list(set(', '.join(x).split(', '))))})
    
    grouped_df
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-31
      • 1970-01-01
      • 2019-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-26
      • 1970-01-01
      相关资源
      最近更新 更多