基于具有不同开始日期的日期创建年-周

2024-10-04 01:28:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个df

date

2021-03-12
2021-03-17
...
2022-05-21
2022-08-17

我试图添加一列year_week,但我的一年工作周从2021-06-28开始,这是七月的第一天

我试过:

df['date'] = pd.to_datetime(df['date'])
df['year_week'] = (df['date'] - timedelta(days=datetime(2021, 6, 24).timetuple()
                               .tm_yday)).dt.isocalendar().week

我对timedelta{}值进行了处理,使得2021-06-28的值为1

但后来我遇到了以前&;超过我的开始日期+1年的日期:

2021-03-12 has a value of 38
2022-08-17 has a value of 8

所以看起来有效期是从2021-06-28+1 year


date            year_week

2021-03-12      38  # LY38
2021-03-17      39  # LY39
2021-06-28      1   # correct
...
2022-05-21      47  # correct
2022-08-17      8   # NY8

有没有办法绕过这个问题?由于我按年度每周汇总数据,因此由于过去&;即将到来的日期。我希望在2021-06-28LY38之前的几天有负日期,表示这是去年的年周,相应地,52+的年周或NY8表示这是下一年的8th


Tags: oftodfdatetimedatevalueyeartimedelta
2条回答

我想 熊猫的活动范围可能会有所帮助

pd.Series(pd.period_range("6/28/2017", freq="W", periods=Number of weeks you want))

这里有一个方法,我增加了两个日期超过一年。您需要从日期列和特定日期的dayofyear之间的差值中获取isocalendar。然后,您可以根据特定日期的year选择不同的场景。对不同的结果格式使用np.select

#dummy dataframe
df = pd.DataFrame(
    {'date': ['2020-03-12',  '2021-03-12',  '2021-03-17', '2021-06-28',  
              '2022-05-21', '2022-08-17', '2023-08-17']
    }
)

# define start date
d = pd.to_datetime('2021-6-24')

# remove the nomber of day of year from each date
s = (pd.to_datetime(df['date']) - pd.Timedelta(days=d.day_of_year)
    ).dt.isocalendar()

# get the difference in year
m = (s['year'].astype('int32') - d.year)

# all condition of result depending on year difference
conds = [m.eq(0), m.eq(-1), m.eq(1), m.lt(-1), m.gt(1)]
choices =  ['', 'LY','NY',(m+1).astype(str)+'LY', '+'+(m-1).astype(str)+'NY']

# create the column
df['res'] = np.select(conds, choices) + s['week'].astype(str)

print(df)
         date     res
0  2020-03-12  -1LY38
1  2021-03-12    LY38
2  2021-03-17    LY39
3  2021-06-28       1
4  2022-05-21      47
5  2022-08-17     NY8
6  2023-08-17   +1NY8

相关问题 更多 >