Python Pandas Timedelta 以月为单位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40923820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas Timedelta in months
提问by Keiku
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
回答by Psidom
Update for pandas 0.24.0:
熊猫 0.24.0 更新:
Since 0.24.0 has changed the api to return MonthEndobject from period subtraction, you could do some manual calculation as follows to get the whole month difference:
由于 0.24.0 已将 api 更改为从周期减法中返回MonthEnd对象,您可以按如下方式进行一些手动计算以获取整月差异:
12 * (df.today.dt.year - df.date.dt.year) + (df.today.dt.month - df.date.dt.month)
# 0 2
# 1 1
# dtype: int64
Wrap in a function:
包裹在一个函数中:
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
Prior to pandas 0.24.0. You can round the date to Month with to_period()
and then subtract the result:
在熊猫 0.24.0 之前。您可以将日期四舍五入为月份,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
回答by Michael Stokes
you could also try:
你也可以尝试:
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
回答by J Darbyshire
The following will accomplish this:
以下将实现这一点:
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