您好,我希望洗掉按取消日期排序的記錄,因此我只對最近的記錄感興趣。
樣本資料
| ID | 取消日期 | 水果型別 |
|---|---|---|
| 1 | 2021-03-02 | 蘋果 |
| 1 | 2021-01-01 | 蘋果 |
| 2 | 2021-02-01 | 橘子 |
預期產出
| ID | 取消日期 | 水果型別 |
|---|---|---|
| 1 | 2021-03-02 | 蘋果 |
| 2 | 2021-02-01 | 橘子 |
我寫了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
uj5u.com熱心網友回復:
以下是您如何實作這一目標。
下面的代碼會將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)
最后,過濾排名為 1 的資料:
filtered_df = df[df["Rank"] == 1]
filtered_df.head()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/337261.html
