【问题标题】:dedup records(window function pandas)去重记录(窗口函数熊猫)
【发布时间】:2021-12-11 08:05:44
【问题描述】:

您好,我希望删除按取消日期排序的记录,因此我只会对最近的记录感兴趣。

样本数据

id cancel_date type_of_fruit
1 2021-03-02 apple
1 2021-01-01 apple
2 2021-02-01 orange

预期输出

id cancel_date type_of_fruit
1 2021-03-02 apple
2 2021-02-01 orange

我写了SQL方式但是我必须在pandas中实现这个逻辑,请帮助

SELECT 
    * 
FROM 
    (SELECT *, 
            rank() over(partition by id order by cancel_date desc) as rank 
     FROM df 
     ORDER BY id, cancel_date DESC) a 
where rank = 1

【问题讨论】:

    标签: python sql pandas database dataframe


    【解决方案1】:

    以下是实现这一目标的方法。

    以下代码会将cancel_date 列转换为datetime 对象,因为您想使用cancel_date 对其进行排序:

    #--if cancel_date is a string, then this code will convert to datetime--
    
    import pandas as pd
    df['cancel_date']= pd.to_datetime(df['cancel_date'])
    

    接下来在id 上对表进行分组(这类似于SQL 中的分区),然后使用cancel_date 列以descending 的顺序进行排序。下面的代码将实现相同的效果:

    df["Rank"] = df.groupby("id")["cancel_date"].rank(method="first", ascending= False)
    

    最后过滤rank为1的数据:

    filtered_df = df[df["Rank"] == 1]
    filtered_df.head()
    

    【讨论】:

      猜你喜欢
      • 2017-03-30
      • 2018-07-10
      • 1970-01-01
      • 2020-04-21
      • 2021-03-30
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      • 2019-12-08
      相关资源
      最近更新 更多