我有一个这样的DataFrame:

import pandas as pd

df = pd.DataFrame({'id':[1,2,3,4,5,6,7,8,9,10], 'name': ['mary','mary','mary','tom','tom','john','sarah','tom','tom','tom'], 'age': [30,30,30,25,25,28,36,25,25,25]})

    id    name  age
0    1    mary   30
1    2    mary   30
2    3    mary   30
3    4     tom   25
4    5     tom   25
5    6    john   28
6    7   sarah   36
7    8     tom   25
8    9     tom   25
9   10     tom   25

它上有多个重复的行(不考虑‘id’列).

我只想删除尾部重复的行,保留第一行(不考虑‘id’列).

我希望得到这样的消息:

    id    name  age
0    1    mary   30
1    2    mary   30
2    3    mary   30
3    4     tom   25
4    5     tom   25
5    6    john   28
6    7   sarah   36
7    8     tom   25

我找不到使用DROP_DUPLICATES解决这个问题的方法.

推荐答案

Code

cols = ['name', 'age'] # column to chk duplicate
grp = df[cols].ne(df[cols].shift()).any(axis=1).cumsum() # make duplicate group
cond = grp.shift().ne(grp.max())
输出 = df[cond]

输出

   id   name  age
0   1   mary   30
1   2   mary   30
2   3   mary   30
3   4    tom   25
4   5    tom   25
5   6   john   28
6   7  sarah   36
7   8    tom   25

Intermediate

df                    grp   grp.shift()   cond <- grp.shift() != 5
   id   name  age    
0   1   mary   30      1       NaN        True
1   2   mary   30      1       1.0        True
2   3   mary   30      1       1.0        True
3   4    tom   25      2       1.0        True
4   5    tom   25      2       2.0        True
5   6   john   28      3       2.0        True
6   7  sarah   36      4       3.0        True
7   8    tom   25      5       4.0        True
8   9    tom   25      5       5.0        False
9  10    tom   25      5       5.0        False

Python相关问答推荐

如何调整spaCy token 化器,以便在德国模型中将数字拆分为行末端的点

Locust请求中的Python和参数

根据条件将新值添加到下面的行或下面新创建的行中

即使在可见的情况下也不相互作用

根据不同列的值在收件箱中移动数据

Pandas - groupby字符串字段并按时间范围 Select

如何让Flask 中的请求标签发挥作用

用NumPy优化a[i] = a[i-1]*b[i] + c[i]的迭代计算

如何在solve()之后获得症状上的等式的值

"使用odbc_connect(raw)连接字符串登录失败;可用于pyodbc"

Godot:需要碰撞的对象的AdditionerBody2D或Area2D以及queue_free?

如何在表中添加重复的列?

python中的解释会在后台调用函数吗?

网格基于1.Y轴与2.x轴显示在matplotlib中

Pandas—堆栈多索引头,但不包括第一列

Python类型提示:对于一个可以迭代的变量,我应该使用什么?

jsonschema日期格式

如何根据一定条件生成段id

如何在PYTHON中向单元测试S Side_Effect发送额外参数?

如何在Polars中处理用户自定义函数的多行结果?