(Pandas) 删除由 GroupBy 创建的重复组

use*_*377 3 python data-manipulation pandas pandas-groupby

我想通过自定义 ID 创建组,然后消除某些列中重复的组。

例如

| id | A   | B  |
|----|-----|----|
| 1  | foo | 40 |
| 1  | bar | 50 |
| 2  | foo | 40 |
| 2  | bar | 50 |
| 2  | cod | 0  |
| 3  | foo | 40 |
| 3  | bar | 50 |
Run Code Online (Sandbox Code Playgroud)

| id | A   | B  |
|----|-----|----|
| 1  | foo | 40 |
| 1  | bar | 50 |
| 2  | foo | 40 |
| 2  | bar | 50 |
| 2  | cod | 0  |
Run Code Online (Sandbox Code Playgroud)

这里我按 id 分组,然后删除了 3 个,因为如果我们只考虑 A 列和 B 列,它们是相同的,而第 2 组有一些重复的行,但它不是精确的副本。

我尝试过循环组,但即使只有大约 12.000 个组,它也非常慢。一个可能的复杂情况是组的大小可变。

这是我一直在研究的解决方案,但它花费了很长时间,没有明显的重复点击(我知道这个数据库中存在)

grps = datafinal.groupby('Form_id') 
unique_grps={}

first=True
for lab1, grp1 in grps:
    if first:
        unique_grps[lab1] = grp1
        first=False
        continue
    for lab2, grp2 in unique_grps.copy().items():
        if grp2[['A','B']].equals(grp1[['A','B']]):
            print("hit")
            continue
        unique_grps[lab1] = grp1
Run Code Online (Sandbox Code Playgroud)

WeN*_*Ben 5

Using agg tuple and duplicated

s=df.groupby('id').agg(tuple).sum(1).duplicated()
df.loc[df.id.isin(s[~s].index)]
Out[779]: 
   id    A   B
0   1  foo  40
1   1  bar  50
2   2  foo  40
3   2  bar  50
4   2  cod   0
Run Code Online (Sandbox Code Playgroud)

More info : Right now , everything within the group is in one tuple

df.groupby('id').agg(tuple).sum(1)
Out[780]: 
id
1            (foo, bar, 40, 50)
2    (foo, bar, cod, 40, 50, 0)
3            (foo, bar, 40, 50)
dtype: object
Run Code Online (Sandbox Code Playgroud)

Update

from natsort import natsorted
s=df.groupby('id').agg(tuple).sum(1).map(natsorted).map(tuple).duplicated()
Run Code Online (Sandbox Code Playgroud)