2016-12-02 66 views
5

我如何计算使用熊猫过去的月份?我写了以下内容,但是这段代码并不优雅。你能告诉我更好的方法吗?熊猫时代月在

import pandas as pd 

df = pd.DataFrame([pd.Timestamp('20161011'), 
        pd.Timestamp('20161101') ], columns=['date']) 
df['today'] = pd.Timestamp('20161202') 

df = df.assign(
    elapsed_months=(12 * 
        (df["today"].map(lambda x: x.year) - 
        df["date"].map(lambda x: x.year)) + 
        (df["today"].map(lambda x: x.month) - 
        df["date"].map(lambda x: x.month)))) 
# Out[34]: 
#   date  today elapsed_months 
# 0 2016-10-11 2016-12-02    2 
# 1 2016-11-01 2016-12-02    1 

回答

7

可以四舍五入日期到本月与to_period(),然后减去结果:

df['elapased_months'] = df.today.dt.to_period('M') - df.date.dt.to_period('M') 

df 
#   date  today elapased_months 
#0 2016-10-11 2016-12-02    2 
#1 2016-11-01 2016-12-02    1 
+1

这样,elapased_months dtype是“object”,因此我通过使用pd.to_numeric()将“object”转换为“int64”。谢谢您的回答。 – Keiku

1

下面将做到这一点:

df["elapsed_months"] = ((df["today"] - df["date"]). 
         map(lambda x: round(x.days/30))) 


# Out[34]: 
#   date  today elapsed_months 
# 0 2016-10-11 2016-12-02    2 
# 1 2016-11-01 2016-12-02    1 
+0

对不起,没有解释。这样,2016-11-30和2016-12-02之间的月份就是0.我想在这种情况下得到1。但它有帮助。谢谢您的回答。 – Keiku

2

,你也可以尝试:

df['months'] = (df['today'] - df['date'])/np.timedelta64(1, 'M') 
df 
#  date  today months 
#0 2016-10-11 2016-12-02 1.708454 
#1 2016-11-01 2016-12-02 1.018501