我需要一個函式,將日期列分組為關于某些開始和結束日期(1 年間隔)的 n 天期間。要為資料框中的每個日期分配一個季度(約 90 天),我使用了下面的代碼,這不是很整潔(我也想在 30 天的時間內重復使用它)
def get_quarter(row, start_date, col_name):
# date = row['TRN_DT']
date = row[col_name]
if date >= start_date and date <= start_date timedelta(days = 90):
return 0
if date > start_date timedelta(days = 90) and date <= start_date timedelta(180):
return 1
if date > start_date timedelta(180) and date <= start_date timedelta(270):
return 2
return 3
它基本上逐行檢查當前日期所屬的間隔。我想知道是否有更好的方法來做到這一點。pandas.Series.dt.to_period() 不會這樣做,因為它使用日歷年作為參考 --start 01.Jan, end 31.Dec; 也就是說,16.Jan.XXXX 將始終在 Q1;如果開始日期是 6 月 16 日,我想要的是 16.Jan 在第三季度。謝謝
uj5u.com熱心網友回復:
FTR,一種可能的解決方案是根據 , 移動系列中的每個日期start_date,以模擬start_date年初:
>>> start_date = pd.to_datetime("2021-06-16")
>>> dates_series = pd.Series([pd.to_datetime("2020-01-16"), pd.to_datetime("2020-04-16")], name="dates")
0 1
1 2
Name: dates, dtype: int64
我們計算當前日期和同一年年初之間的差異。
>>> offset = start_date - start_date.replace(month=1, day=1)
>>> offset
166 days 00:00:00
我們將所有日期移動到同一個offser 以計算“新季度”
>>> (dates - offset).dt.quarter
0 3
1 4
Name: dates, dtype: int64
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/434268.html
標籤:python-3.x 熊猫 数据框 日期 熊猫-groupby
上一篇:如何在火花中過濾可變日期?
