删除记录(窗口函数pandas)



你好,我希望删除按取消日期订购的记录,因此我只对最近的记录感兴趣。

示例数据
<表类>idcancel_datetype_of_fruittbody><<tr>12021-03-02苹果12021-01-01苹果22021-02-01橙色

您可以这样做:

下面的代码将把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()

最新更新