我下面有一个数据框表,其中包含新值和旧值。我想删除所有旧值,同时保留新值。
ID Name Time Comment
0 Foo 12:17:37 Rand
1 Foo 12:17:37 Rand1
2 Foo 08:20:00 Rand2
3 Foo 08:20:00 Rand3
4 Bar 09:01:00 Rand4
5 Bar 09:01:00 Rand5
6 Bar 08:50:50 Rand6
7 Bar 08:50:00 Rand7
因此,它应如下所示:
ID Name Time Comment
0 Foo 12:17:37 Rand
1 Foo 12:17:37 Rand1
4 Bar 09:01:00 Rand4
5 Bar 09:01:00 Rand5
我尝试使用下面的代码,但这删除了1个新值和1个旧值。
df[~df[['Time', 'Comment']].duplicated(keep='first')]
谁能提供正确的解决方案?
我认为您可以使用此解决方案to_timedelta
,如果需要按column的最大值进行过滤Time
:
df.Time = pd.to_timedelta(df.Time)
df = df[df.Time == df.Time.max()]
print (df)
ID Name Time Comment
0 0 Foo 12:17:37 Rand
1 1 Foo 12:17:37 Rand1
编辑的解决方案是类似的,只添加了groupby
:
df = df.groupby('Name', sort=False)
.apply(lambda x: x[x.Time == x.Time.max()])
.reset_index(drop=True)
print (df)
ID Name Time Comment
0 0 Foo 12:17:37 Rand
1 1 Foo 12:17:37 Rand1
2 4 Bar 09:01:00 Rand4
3 5 Bar 09:01:00 Rand5
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句