从周日开始,将第53周和第1周合并为同一周。

问题描述 投票:0回答:1

你好,我有以下数据:指数,星期的一天,星期号,时间。

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周。-1月1日的那一周是第1周 周数从周日开始 第1周是整整7天的一周 也就是说12月29日、30日和31日也是第1周。-当我在这个数据集中有很多年的时候,为了让这个也能工作。

在这一年里,这意味着把所有的53都改为1,但我想可能还有其他年份不能用。所以为了得到一个一般的规则,我意识到如果1月1日是在周日,我不需要改变任何东西,所以我想先检查一下每年的情况,如果1月1日不是在周日,就把前一个周日和那个周日之间的所有周号都改为1。我想到的另一个方案是找出前一个星期天的星期号,然后将该年所有与前一个星期天相同的星期号改为1.对于这两个方案,我都需要在df中做一个条件,只过滤掉某些行,但是当我只想显示df中的一列时,我该怎么做呢?意思是如果我做:

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

那么这将会显示所有列的总数 而我只想在这些条件下显示 "星期 "这一列

所以,我将如何做,而且,这一切听起来超级复杂的我。是否有一个更简单更有效的方法,我忽略了?

谢谢你!我有以下数据:索引

python pandas conditional-statements week-number
1个回答
0
投票

您可以使用 mod 操作符。这将给你除以给定数字后的余数。因此。52 % 52 = 00 % 52 = 0. Mod只有当你从0开始计数时才真正有效,所以你必须减去一个fisrt,见下文。

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

0
投票

使用 datetime 包中描述的那样。如何在Python中找到周日开始的周数?


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

0
投票

所以这是我最后想到的。从性能上看,这个怎么样?

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']])
© www.soinside.com 2019 - 2024. All rights reserved.