pandas 几个月来的时间三角洲 [英] Pandas Timedelta in months

查看:67
本文介绍了 pandas 几个月来的时间三角洲的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I calculate the elapsed months using pandas? I have write the following, but this code is not elegant. Could you tell me a better way?

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

推荐答案

更新为熊猫0.24.0 :

由于0.24.0更改了api以从周期减法返回 MonthEnd 对象,因此您可以按如下所示进行一些手动计算以获得整个月的差额:

Since 0.24.0 has changed the api to return MonthEnd object from period subtraction, you could do some manual calculation as follows to get the whole month difference:

12 * (df.today.dt.year - df.date.dt.year) + (df.today.dt.month - df.date.dt.month)

# 0    2
# 1    1
# dtype: int64

包装一个函数:

def month_diff(a, b):
    return 12 * (a.dt.year - b.dt.year) + (a.dt.month - b.dt.month)

month_diff(df.today, df.date)
# 0    2
# 1    1
# dtype: int64


熊猫0.24.0之前.您可以使用to_period()将日期四舍五入到Month,然后减去结果:


Prior to pandas 0.24.0. You can round the date to Month with to_period() and then subtract the result:

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

这篇关于 pandas 几个月来的时间三角洲的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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