Skip to main content
 首页 » 编程设计

python之根据更复杂的条件删除 Pandas 中的行

2025年05月04日22dyllove98

我有以下数据框:

time        id  type 
2012-12-19  1   abcF1 
2013-11-02  1   xF1yz 
2012-12-19  1   abcF1 
2012-12-18  1   abcF1 
2013-11-02  1   xF1yz 
2006-07-07  5   F5spo 
2006-07-06  5   F5spo 
2005-07-07  5   F5abc 

对于给定的 ID,我需要找到最大日期。

对于那个最大日期,我需要检查类型。

如果类型与最大日期的类型不同,我必须删除给定 ID 的每一行。

目标数据框示例:

time        id  type 
<deleted because for id 1 the date is not the max value and the type differs from the type of the max date for id 1> 
2013-11-02  1   xF1yz 
<deleted because for id 1 the date is not the max value and the type differs from the type of the max date for id 1> 
<deleted because for id 1 the date is not the max value and the type differs from the type of the max date for id 1> 
2013-11-02  1   xF1yz 
2006-07-07  5   F5spo 
2006-07-06  5   F5spo //kept because although the date is not max, it has the same type as the row with the max date for id 5 
<deleted because for id 5 the date is not the max value and the type differs from the type of the max date for id 5> 

我怎样才能做到这一点? 我是 pandas 的新手,正在尝试学习使用该库的正确方法。

请您参考如下方法:

使用DataFrameGroupBy.idxmax对于获取最大值的索引,仅过滤列 id 和 type 以及 DataFrame.merge :

df = df.merge(df.loc[df.groupby('id')['time'].idxmax(), ['id','type']]) 
print (df) 
        time  id   type 
0 2013-11-02   1  xF1yz 
1 2013-11-02   1  xF1yz 
2 2006-07-07   5  F5spo 
3 2006-07-06   5  F5spo 

或者使用DataFrame.sort_values与 DataFrame.drop_duplicates :

df = df.merge(df.sort_values('time').drop_duplicates('id', keep='last')[["id", "type"]])