Pandas 在新列中计算最近几个月的数据

Pandas calculate last few months data in new column

我有以下格式的数据框;

ID | 01/01/2016 | 02/03/2016 | 02/15/2016 | ........
11 | 100        | 200        | 100        | ........

我正在尝试计算新列中最近 3 个月数据的总和。预期输出应如下所示;

ID | 01/01/2016 | 02/03/2016 | 02/15/2016 | ........ | Last 3 Months
11 | 100        | 200        | 100        | ........ | 300

作为解决方案,我需要选择今天的日期并将其与列中的日期进行比较,然后对值求和。但是,我不确定该怎么做?能给点建议吗?

谢谢。

这并不像最初看起来那么简单。您需要确定如何处理每年的变化以及每个月的天数不同。我使用一个简单的函数来做到这一点。您可以调整下面的代码以满足您的需要,但它应该可以帮助您入门。

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)