【问题标题】:Drop duplicate rows from a pandas DataFrame whose timestamps are within a specified range or duration从时间戳在指定范围或持续时间内的 pandas DataFrame 中删除重复行
【发布时间】:2018-04-30 16:15:10
【问题描述】:

我有一个这样的数据框:

Subject Verb    Object  Date
---------------------------------
Bill    Ate     Food    7/11/2015
Steve   Painted House   8/12/2011
Bill    Ate     Food    7/13/2015
Steve   Painted House   8/25/2011

我想删除所有重复项,其中重复项被定义为具有相同的主语、动词、宾语,并且在 X 天范围内(在我的示例中:5 天)。

Subject Verb    Object  Date
---------------------------------
Bill    Ate     Food    7/11/2015
Steve   Painted House   8/12/2011
Steve   Painted House   8/25/2011

两个“Steve - Painted - House”实例都没有被删除,因为它们超出了 5 天的窗口期。

我知道我可以使用一些数据结构和 DataFrame 的 iterrows 方法来做到这一点,但是有没有办法使用 Pandas drop_duplicates 做到这一点?

【问题讨论】:

    标签: python pandas dataframe duplicates


    【解决方案1】:

    duplicated + diffgroupby 结合使用来确定要删除的行。

    c = ['Subject', 'Verb', 'Object']
    
    def f(x):
        return x[c].duplicated() & x.Date.diff().dt.days.lt(5)
    
    df = df.sort_values(c)
    df[~df.groupby(c).apply(f).values]
    
      Subject     Verb Object       Date
    0    Bill      Ate   Food 2015-07-11
    1   Steve  Painted  House 2011-08-12
    3   Steve  Painted  House 2011-08-25
    

    【讨论】:

    • 您的编辑版本(您不调用 df.columns.difference)是一项改进,因为这允许 DataFrame 中存在不包含在重复条件中的其他列。
    • @mikeronayne 谢谢,我已经重构了我的答案,希望它对你更好。 :)
    • 也许是np.close?
    猜你喜欢
    • 2022-10-14
    • 1970-01-01
    • 2018-04-07
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 2011-06-24
    • 2013-08-22
    • 1970-01-01
    相关资源
    最近更新 更多