从星期日开始将第53周和第1周设为同一周

时间:2020-05-03 10:45:18

标签: python pandas conditional-statements week-number

嗨,我有以下数据:
索引,星期几,星期几,Fecha

360      Friday       52 2019-12-27
361    Saturday       52 2019-12-28
362      Sunday       53 2019-12-29
363      Monday       53 2019-12-30
364     Tuesday       53 2019-12-31
365   Wednesday        1 2020-01-01
366    Thursday        1 2020-01-02
367      Friday        1 2020-01-03
368    Saturday        1 2020-01-04
369      Sunday        2 2020-01-05
370      Monday        2 2020-01-06

我想要:
-包含1月1日的一周是第1周
-让星期几从星期日开始
-将第1周作为7天的完整周,这意味着12月29日,30日和31日也将获得第1周。
-当我在这个数据集中有很多年时,也可以使用它。

在这一特定年份,这意味着将所有53都改为1,但是我认为可能还有其他年份无法正常工作。因此,为了获得一般规则,我意识到如果一月的第一天是星期日,那么我不需要进行任何更改,因此我想首先检查一下每年的情况,如果一月的第一天不是在星期日,将前一个星期日和该星期日之间的所有星期编号更改为1。我想到的另一种选择是找出前一个星期日没有哪个星期,然后将该年的所有星期编号更改为与前一个星期日相同的编号,到1。 对于这两者,我都需要在df中执行一个条件以仅过滤出某些行,但是当我只想显示该df的一列时该怎么做?我是否愿意做的意思:

totals[(totals['Fecha'].dt.month==1) & (totals['Fecha'].dt.day==1) & (totals['Fecha'].dt.year==i)]

然后这将显示总计的所有列,而我需要这些条件以及仅查看“周日”列。

所以我该怎么做,而且,这一切对我来说都非常复杂。有没有一种更容易/更有效的方法被我忽略了?

谢谢!

4 个答案:

答案 0 :(得分:1)

这就是我最后要提出的。这种表现如何?

totals['Fecha']=pd.to_datetime(totals['Fecha'], format='%d/%m/%Y') #change type to datetime
totals['Day of week']=totals['Fecha'].dt.weekday_name   #create day of week 'Sunday, Monday, etc'
totals['Week no']=totals['Fecha'].dt.strftime('%U').astype(int)+1 #create week no's with Sunday as first day of week

for i in set(totals['Fecha'].dt.year):
    if i!=2019: #because for the first year we don't have a previous end of year
        first_day_of_year=str(i)+'-01-01' 
        # if there are any rows where the day of the week of the first day of the year equals 'Sunday'
        if any(totals['Day of week'].where(totals['Fecha']==first_day_of_year)!='Sunday'):

        # then for the year before, change all the last week no's to one
            last_week=max(totals['Week no'].where(totals['Fecha'].dt.year==i-1))
            totals.loc[(totals['Week no']==last_week)&(totals['Fecha'].dt.year==i-1), 'Week no']=1

print(totals[['Day of week', 'Week no', 'Fecha']])

答案 1 :(得分:0)

您可以使用mod运算符。这将为您提供除以给定数字后的余数。因此,52 % 52 = 00 % 52 = 0。仅当从0开始计数时,Mod才真正起作用,因此您必须减去一个常数,如下所示:

my_week = 53
my_bounded_week = ((my_week - 1) % 52) + 1
# First minus one to make the series start at 0.
# Then add one after the mod to make the series start at 1

print(my_bounded_week)
# prints 1

答案 2 :(得分:0)

按照以下StackOverflow答案中所述使用datetime软件包:How can I find week numbers with weeks starting on Sunday in Python?

答案 3 :(得分:0)

好像您需要自己的自定义业务日历,我们可以使用一个小功能来创建一个。

假设您要从每个日历年的第一个日历日开始创建日历,那么它将起作用。

一个警告是我已经多年没有写这个了,我会留给你:)

用法

df = business_cal('01-01-2019','01-01-2020')

print(df.head(5))

        date  weeks  dayofmonth  dayofweek daynameofweek
0 2018-12-30      1          30          6        Sunday
1 2018-12-31      1          31          0        Monday
2 2019-01-01      1           1          1       Tuesday
3 2019-01-02      1           2          2     Wednesday
4 2019-01-03      1           3          3      Thursday

功能。

def business_cal(start,end):
    """
    Function that returns a calendar year given a start and end date.
    Constrains - week must start on Sunday if 01/01/2020 is not Sunday,
    we take the last Sunday of the previous year.
    """
    start_date = pd.to_datetime(start)
    
    if start_date.weekday() != 6:
        start_date = start_date - pd.DateOffset(days=(start_date.weekday() + 1))
    else:
        start_date


    dates = pd.date_range(start_date,end,freq='7D')
    
    df = pd.DataFrame(dates,columns=['date'])
    # grab week numbers.
    df['weeks'] = df.index + 1 
    df1 = df.set_index('date').resample('D').ffill().reset_index()
    
    df1['dayofmonth'] = df1['date'].dt.day
    df1['dayofweek'] = df1['date'].dt.dayofweek
    df1['daynameofweek'] = df1['date'].dt.day_name()
    return df1
相关问题