将日期列分组为 n 天时间段
Group date column into n-day periods
我需要一个函数,根据某些开始日期和结束日期(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 进入第三季度。谢谢
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
我们将所有日期移动到同一个报价以计算“新季度”
>>> (dates - offset).dt.quarter
0 3
1 4
Name: dates, dtype: int64
我需要一个函数,根据某些开始日期和结束日期(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 进入第三季度。谢谢
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
我们将所有日期移动到同一个报价以计算“新季度”
>>> (dates - offset).dt.quarter
0 3
1 4
Name: dates, dtype: int64