pandas 日期时间:计算两列中的日期之间的星期数 [英] Pandas Datetime: Calculate Number of Weeks Between Dates in Two Columns

查看:138
本文介绍了 pandas 日期时间:计算两列中的日期之间的星期数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数据框,其中有两列包含日期,并且我想创建一个新列,其值是这些日期之间的月数.

Let's say I have a dataframe with two columns that contain dates, and I want to create a new columns whose value is the number of months between those dates.

>df

Index   Date1         Date2
1       2012/03/07    2013/03/16
2       2012/12/05    2012/12/25
3       2010/06/30    2013/05/19
4       2002/11/02    2011.06.08


df["Date1"]= pd.to_datetime(df["Date1"])
df["Date2"]= pd.to_datetime(df["Date2"])

Date1将始终在date2之前.我目前执行此操作的方法大约需要10个步骤,而且我敢肯定有一种更简单的方法可以执行此操作.有想法吗?

Date1 will always be before date2. My current method of doing this requires about 10 steps, and I'm pretty sure there's an easier way to do this. Thoughts?

推荐答案

参见此链接: http://pandas.pydata.org/pandas-docs/dev/timeseries.html#time-deltas

(df['Date2']-df['Date1']).apply(lambda x: x/np.timedelta64(1,'M'))

对于numpy> = 1.7(如果使用1.6.1,请参见链接)

for numpy >=1.7 (see the link if you are using 1.6.1)

我不确定它将如何处理分数. (通常我将除以np.timedelta64(1,'D')然后除以30,得出小数月(作为浮点数)

I am not sure what it will do with the fraction. (usually I would divide by np.timedelta64(1,'D') then divide by say 30 to make a fractional num of months (as a float)

这篇关于 pandas 日期时间:计算两列中的日期之间的星期数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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