如果 create_date 欄位不對應于 from_date 和 to_date 之間的時間段,我只想使用 group by 'indicator' 提取大索引記錄,并且記錄對應于 from_date 到 end_date 之間的時間段。
from_date = '2022-01-01'
to_date = '2022-04-10'
indicator create_date
0 A 2022-01-03
1 B 2021-12-30
2 B 2021-07-11
3 C 2021-02-10
4 C 2021-09-08
5 C 2021-07-24
6 C 2021-01-30
這是我想要的結果:
indicator create_date
0 A 2022-01-03
2 B 2021-07-11
6 C 2021-01-30
找了很久的解決方法,但是只找到了“如何獲取最小值的索引”的方法,找不到比較索引號的方法。
uj5u.com熱心網友回復:
你可以試試
df['create_date'] = pd.to_datetime(df['create_date'])
m = df['create_date'].between(from_date, to_date)
df_ = df[~m].groupby('indicator', as_index=False).apply(lambda g: g.loc[[max(g.index)]]).droplevel(level=0)
out = pd.concat([df[m], df_], axis=0).sort_index()
print(out)
indicator create_date
0 A 2022-01-03
2 B 2021-07-11
6 C 2021-01-30
uj5u.com熱心網友回復:
indicator您可以為每個創建的最大索引值創建輔助列DataFrameGroupBy.idxmax,最后選擇行DataFrame.loc:
df2 = df.loc[df.assign(tmp=df.index).groupby('indicator')['tmp'].idxmax()]
print (df2)
indicator create_date
0 A 2022-01-03
2 B 2021-07-11
6 C 2021-01-30
編輯:如果需要僅在與 join by 的from_date, to_date使用之間不匹配的值中查找最大索引:boolean indexingconcat
from_date = '2022-01-01'
to_date = '2022-04-10'
df['create_date'] = pd.to_datetime(df['create_date'])
m = df['create_date'].between(from_date, to_date)
df2 = df.loc[df.assign(tmp=df.index)[~m].groupby('indicator')['tmp'].idxmax()]
print (df2)
indicator create_date
2 B 2021-07-11
6 C 2021-01-30
df = pd.concat([df[m], df2])
print (df)
indicator create_date
0 A 2022-01-03
2 B 2021-07-11
6 C 2021-01-30
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/474538.html
