Pandas 日期时间:计算两列中日期之间的周数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17414130/
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 Datetime: Calculate Number of Weeks Between Dates in Two Columns
提问by Olga Mu
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 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?
日期 1 将始终在日期 2 之前。我目前执行此操作的方法大约需要 10 个步骤,而且我很确定有一种更简单的方法可以做到这一点。想法?
回答by Jeff
see this link: http://pandas.pydata.org/pandas-docs/dev/timeseries.html#time-deltas
请参阅此链接:http: //pandas.pydata.org/pandas-docs/dev/timeseries.html#time-deltas
(df['Date2']-df['Date1']).apply(lambda x: x/np.timedelta64(1,'M'))
for numpy >=1.7 (see the link if you are using 1.6.1)
对于 numpy >=1.7(如果您使用的是 1.6.1,请参阅链接)
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)
我不确定它会对分数做什么。(通常我会除以np.timedelta64(1,'D')然后除以 30 来得出月份的小数(作为浮点数)
回答by Kevin Pluck
I'm not sure how to do it in python but the steps I would do:
我不知道如何在 python 中做到这一点,但我会做的步骤:
- Convert dates into number of days since the epoch
- Subtract date1 from date2
- Divide by 7
- 将日期转换为自纪元以来的天数
- 从日期 2 中减去日期 1
- 除以 7

