這並不像最初看起來那麼簡單。你需要確定你將如何處理每年的變化,並在每個月有不同的天數。我使用一個簡單的函數來完成此操作你可以調整下面的代碼來滿足你的需求,但它應該讓你開始。
from __future__ import division, print_function
def subtract_months(m):
'''subtracts specified number of months from current date
Parameters
----------
m : integer
how many months to subtract from today's date
Returns
-------
date : datetime value'''
yr = dt.date.today().year
mon = dt.date.today().month - m
day = dt.date.today().day
# test whether we went into another year
if mon<=0:
yr -= 1
mon = 12 + mon
# test whether we have exceeded maximum number of days in month
if day>calendar.monthrange(yr,mon)[1]:
day = calendar.monthrange(yr,mon)[1]
return dt.date(yr,mon,day)
import pandas as pd
import datetime as dt
import calendar
dates = pd.date_range('20160101','20170101',freq='1D')
data = pd.np.random.randint(0,100,(5,367))
df = pd.DataFrame(data=data,index=list('ABCDE'),columns=dates)
# now add a new column
df['Last 3 Months'] = df.T.truncate(before=subtract_months(3),after=dt.date.today()).sum(axis=0)
這篇文章幫了我很多!很好的例子。謝謝 – merimini