【问题标题】:Keep the most recent values and drop older rows (pandas)保留最新值并删除旧行(熊猫)
【发布时间】:2017-05-24 16:29:33
【问题描述】:

我在下面有一个数据框表,其中包含新值和旧值。我想删除所有旧值,同时保留新值。

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')]

谁能提供正确的解决方案?

【问题讨论】:

    标签: python datetime pandas dataframe


    【解决方案1】:

    我认为您可以将此解决方案与to_timedelta 一起使用,如果需要按列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
    

    【讨论】:

    • 由于 cmets 格式不佳,您可以编辑问题吗?
    • 如果解决方案不起作用,请尝试使用所需的输出创建minimal, complete, and verifiable example。
    • 会的。顺便说一句,这可行,但不是我想要的。让我更新一下问题。
    【解决方案2】:

    您可以将组的最大值合并回原始 DF:

    df['Time'] = pd.to_timedelta(df['Time'])
    
    In [35]: pd.merge(df, df.groupby('Name', as_index=False)['Time'].max(), on=['Name','Time'])
    Out[35]:
       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
    

    解释:

    In [36]: df.groupby('Name', as_index=False)['Time'].max()
    Out[36]:
      Name     Time
    0  Bar 09:01:00
    1  Foo 12:17:37
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 2020-11-10
      • 1970-01-01
      • 2013-07-10
      相关资源
      最近更新 更多