我想使用這個資料框
df = pd.DataFrame({'Serial' : ['A1', 'A1', 'A1', 'B1','B1', 'B1'],'Day' : ['01.01.2022', '01.01.2022', '01.01.2021', '01.01.2019', '01.01.2019', '01.01.2020'],'Else' : ['a', 'b', 'c', 'd','e', 'f']})
按 Serial 分組并僅保留具有 max(Day) 的行,即這是我的預期輸出:
| 連續劇 | 天 | 別的 |
|---|---|---|
| A1 | 01.01.2022 | 一個 |
| A1 | 01.01.2022 | b |
| B1 | 01.01.2020 | F |
我成功計算了最大值,但不知道如何使用它進行過濾以獲得預期的輸出。
df['Day']= pd.to_datetime(df['Day'], format="%d.%m.%Y")
df = df.groupby(['Serial'])['Day'].max()
uj5u.com熱心網友回復:
這是一種方法
# convert the date to the YMD format for finding max
df['Day2']=pd.to_datetime(df['Day'], dayfirst=True)
# group on Serial, and return the max value against all rows of grouped result
# compare and filter where max date matches the date in DF
out=df.loc[df['Day2'].eq(df.groupby('Serial')['Day2'].transform(max))].drop(columns='Day2')
out
Serial Day Else
0 A1 01.01.2022 a
1 A1 01.01.2022 b
5 B1 01.01.2020 f
uj5u.com熱心網友回復:
基于這個答案,你應該首先得到你的日期最大的所有索引。然后你可以在你的資料框上使用你的索引。像那樣的東西
df = pd.DataFrame({'Serial' : ['A1', 'A1', 'A1', 'B1','B1', 'B1'],'Day' : ['01.01.2022', '01.01.2022', '01.01.2021', '01.01.2019', '01.01.2019', '01.01.2020'],'Else' : ['a', 'b', 'c', 'd','e', 'f']})
df['Day'] = pd.to_datetime(df['Day'], format="%d.%m.%Y")
idx = df.groupby(['Serial'])['Day'].transform(max) == df['Day']
print(df[idx])
這給你你的結果如下
Serial Day Else
0 A1 2022-01-01 a
1 A1 2022-01-01 b
5 B1 2020-01-01 f
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/536967.html
上一篇:Java格式化GMT日期
