给定数据帧:
df = pd.DataFrame({'col1': ['A', 'A', 'A','B','B'], 'col2': ['type1', 'type2', 'type1', 'type2', 'type1'] , 'hour': ['18:03:30','18:00:48', '18:13:46', '18:11:29', '18:06:31'] })
col1 col2 hour
A type1 18:03:30 # Drop this row as (A type1) already present
A type2 18:00:48
A type1 18:13:46 # keep this row as (A type1) already present.
B type2 18:11:29
B type1 18:06:31
我想根据 col1,col2 删除重复项。
例如。(行 (0(: 类型 1, 行 (2(: 类型 1(
仅保留具有最新小时的行,例如。"(18:13:46(。
我尝试使用groupby基于 col1 返回子集,drop_duplicates将重复项放在 col2 中。我需要找到一种方法来通过条件(最近一小时(
示例代码:
for key, grp in df.groupby('col1'):
grp.drop_duplicates(subset='col2', keep="LATEST OF HOUR")
预期成果:
col1 col2 hour
A type1 18:03:30
A type2 18:00:48
B type2 18:11:29
B type1 18:06:31
编辑添加上下文
我的原始数据帧更大,解决方案还需要适用于:
col1 col2 other hour
A type1 h 18:03:30 # Drop this row as (A type1) already present
A type2 ss 18:00:48
A type1 ll 18:13:46 # keep this row as (A type1) already present
B type2 mm 18:11:29
B type1 jj 18:06:31
它仍然需要根据小时删除列
df.drop_duplicates(['col1','col2'] , keep = 'last')
根据anky_91的评论,我这样解决它:
df.sort_values('hour').drop_duplicates(['col1','col2'] , keep = 'last')
这基于列"小时"进行排序,以便您确保 keep='last' 获取最后一个元素