繁体   English   中英

一个月中的第几周 pandas

[英]Week of a month pandas

我试图在一个月内获得一周,有些月份可能有四个星期,有些可能有五个星期。 对于每个日期,我想知道它属于哪一周。 我最感兴趣的是本月的最后一周。

data = pd.DataFrame(pd.date_range(' 1/ 1/ 2000', periods = 100, freq ='D'))

0  2000-01-01
1  2000-01-02
2  2000-01-03
3  2000-01-04
4  2000-01-05
5  2000-01-06
6  2000-01-07

看到这个答案并决定你想要的哪个星期。

没有内置的东西,所以你需要用apply来计算它。 例如,对于一个简单的“已经过去了多少 7 天”的度量。

data['wom'] = data[0].apply(lambda d: (d.day-1) // 7 + 1)

对于更复杂的(基于日历),使用该答案中的函数。

import datetime
import calendar

def week_of_month(tgtdate):
    tgtdate = tgtdate.to_datetime()

    days_this_month = calendar.mdays[tgtdate.month]
    for i in range(1, days_this_month):
        d = datetime.datetime(tgtdate.year, tgtdate.month, i)
        if d.day - d.weekday() > 0:
            startdate = d
            break
    # now we canuse the modulo 7 appraoch
    return (tgtdate - startdate).days //7 + 1

data['calendar_wom'] = data[0].apply(week_of_month)

在处理具有日期时间索引的数据帧时,我使用了下面的代码。

import pandas as pd
import math

def add_week_of_month(df):
    df['week_in_month'] = pd.to_numeric(df.index.day/7)
    df['week_in_month'] = df['week_in_month'].apply(lambda x: math.ceil(x))
    return df

如果你运行这个例子:

df = test = pd.DataFrame({'count':['a','b','c','d','e']},
                     index = ['2018-01-01', '2018-01-08','2018-01-31','2018-02-01','2018-02-28'])
df.index = pd.to_datetime(df.index)

你应该得到以下数据框

               count  week_in_month

2018-01-01     a              1
2018-01-08     b              2
2018-01-31     c              5
2018-02-01     d              1
2018-02-28     e              4

TL; 博士

import pandas as pd

def weekinmonth(dates):
    """Get week number in a month.
    
    Parameters: 
        dates (pd.Series): Series of dates.
    Returns: 
        pd.Series: Week number in a month.
    """
    firstday_in_month = dates - pd.to_timedelta(dates.dt.day - 1, unit='d')
    return (dates.dt.day-1 + firstday_in_month.dt.weekday) // 7 + 1
    
    
df = pd.DataFrame(pd.date_range(' 1/ 1/ 2000', periods = 100, freq ='D'), columns=['Date'])
weekinmonth(df['Date'])
0     1
1     1
2     2
3     2
4     2
     ..
95    2
96    2
97    2
98    2
99    2
Name: Date, Length: 100, dtype: int64

解释

首先,计算一个月的第一天(来自这个答案: How floor a date to the first date? ):

df = pd.DataFrame(pd.date_range(' 1/ 1/ 2000', periods = 100, freq ='D'), columns=['Date'])
df['MonthFirstDay'] = df['Date'] - pd.to_timedelta(df['Date'].dt.day - 1, unit='d')
df
         Date MonthFirstDay
0  2000-01-01    2000-01-01
1  2000-01-02    2000-01-01
2  2000-01-03    2000-01-01
3  2000-01-04    2000-01-01
4  2000-01-05    2000-01-01
..        ...           ...
95 2000-04-05    2000-04-01
96 2000-04-06    2000-04-01
97 2000-04-07    2000-04-01
98 2000-04-08    2000-04-01
99 2000-04-09    2000-04-01

[100 rows x 2 columns]

从第一天开始获取工作日:

df['FirstWeekday'] = df['MonthFirstDay'].dt.weekday
df
         Date MonthFirstDay  FirstWeekday
0  2000-01-01    2000-01-01             5
1  2000-01-02    2000-01-01             5
2  2000-01-03    2000-01-01             5
3  2000-01-04    2000-01-01             5
4  2000-01-05    2000-01-01             5
..        ...           ...           ...
95 2000-04-05    2000-04-01             5
96 2000-04-06    2000-04-01             5
97 2000-04-07    2000-04-01             5
98 2000-04-08    2000-04-01             5
99 2000-04-09    2000-04-01             5

[100 rows x 3 columns]

现在我可以用工作日的模计算来获得一个月的周数:

  1. 通过df['Date'].dt.day获取月份中的第df['Date'].dt.day ,并确保由于模计算df['Date'].dt.day-1以 0 开头。
  2. 添加工作日数字以确保月份的哪一天开始+ df['FirstWeekday']
  3. 安全地使用一周中 7 天的整数除法,并从 1 // 7 + 1开始在月份中添加 1 以开始周数。

全模计算:

df['WeekInMonth'] = (df['Date'].dt.day-1 + df['FirstWeekday']) // 7 + 1
df
         Date MonthFirstDay  FirstWeekday  WeekInMonth
0  2000-01-01    2000-01-01             5            1
1  2000-01-02    2000-01-01             5            1
2  2000-01-03    2000-01-01             5            2
3  2000-01-04    2000-01-01             5            2
4  2000-01-05    2000-01-01             5            2
..        ...           ...           ...          ...
95 2000-04-05    2000-04-01             5            2
96 2000-04-06    2000-04-01             5            2
97 2000-04-07    2000-04-01             5            2
98 2000-04-08    2000-04-01             5            2
99 2000-04-09    2000-04-01             5            2

[100 rows x 4 columns]

这似乎对我有用

df_dates = pd.DataFrame({'date':pd.bdate_range(df['date'].min(),df['date'].max())})
df_dates_tues = df_dates[df_dates['date'].dt.weekday==2].copy()
df_dates_tues['week']=np.mod(df_dates_tues['date'].dt.strftime('%W').astype(int),4)

你可以得到它减去当前周和当月第一天的那一周,但需要额外的逻辑来处理一年的第一周和最后一周:

def get_week(s):
    prev_week = (s - pd.to_timedelta(7, unit='d')).dt.week
    return (
        s.dt.week
        .where((s.dt.month != 1) | (s.dt.week < 50), 0)
        .where((s.dt.month != 12) | (s.dt.week > 1), prev_week + 1)
    )

def get_week_of_month(s):
    first_day_of_month = s - pd.to_timedelta(s.dt.day - 1, unit='d')
    first_week_of_month = get_week(first_day_of_month)
    current_week = get_week(s)
    return  current_week - first_week_of_month

我获取一个月中的一周的逻辑取决于一年中的一周。

  1. 在数据框中计算一年中的第一个星期
  2. 如果月份不是 1,则获取上一年的最大周月,如果月份是 1,则返回一年中的一周
  3. 如果上个月的最大周等于当月的最大周
  4. 然后返回一年中的当前周与上个月的最大周月加 1 的差值
  5. 否则返回一年中当前周与上个月最大周月的差异

希望这可以解决上面使用的多个逻辑有限制的问题,下面的功能也一样。 这里的 Temp 是使用 dt.weekofyear 计算一年中哪一周的数据框

def weekofmonth(dt1):
    if dt1.month == 1:
        return (dt1.weekofyear)
    else:
        pmth = dt1.month - 1
        year = dt1.year
        pmmaxweek = temp[(temp['timestamp_utc'].dt.month == pmth) & (temp['timestamp_utc'].dt.year == year)]['timestamp_utc'].dt.weekofyear.max()
        if dt1.weekofyear == pmmaxweek:
            return (dt1.weekofyear - pmmaxweek + 1)
        else:
            return (dt1.weekofyear - pmmaxweek)
import pandas as pd
import math

def week_of_month(dt:pd.Timestamp):
    return math.ceil((x-1)//7)+1
dt["what_you_need"] = df["dt_col_name"].apply(week_of_month)

这为您提供了 1-5 周,如果天数>28,则计为第 5 周。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM