每月的周数

时间:2017-12-27 03:52:32

标签: python pandas series

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

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])

使用短数据集它可以工作,但是大数据集需要很多资源

1 个答案:

答案 0 :(得分:0)

问题解决了:

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))