本月的周数 [英] Week number of the month

查看:45
本文介绍了本月的周数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pandas (python) 是否提供了一种从日期系列中轻松获取本月当前周 (1:4) 的方法?

Does pandas (python) offer a way to easily get the current week of the month (1:4) from a date series?

data = {'date': ['2014-05-01', '2014-05-01', '2014-05-02', '2014-05-02', '2014-05-02', '2014-05-02', '2014-05-03', '2014-05-03', '2014-05-04', '2014-05-04']}
df = pd.DataFrame(data, columns = ['date'])
df['date']=pd.to_datetime(df['date'])

def week_of_month(dt):
    """ Returns the week of the month for the specified date.
    """
    first_day = dt.replace(day=1)
    dom = dt.day
    adjusted_dom = dom + first_day.weekday()
    return int(ceil(adjusted_dom/7.0))


df ['week']=np.nan
for i in range(len(df)):
    df ['week'][i] =  week_of_month(df.date.iloc[i])

使用短数据集可以,但使用大数据集需要大量资源

with a short data set it works but with a large data set takes to much resources

推荐答案

问题解决:

data = {'date_x': ['2014-05-01', '2014-05-01', '2014-05-02', '2014-05-02', '2014-05-02', '2014-05-02', '2014-05-03', '2014-05-03', '2014-05-04', '2014-05-04']}
df = pd.DataFrame(data, columns = ['date_x'])
df['date']=pd.to_datetime(df['date_x'])

df['first_day_aux']=pd.to_datetime(df['date_x'][0][:8]+'01') 
df['day']=df['date'].dt.day 
df['adjusted_dom']=df['day']+df['first_day_aux'].dt.dayofweek
df['week']=np.int_(np.ceil(df['adjusted_dom']/7.0))

这篇关于本月的周数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆