Python 在 DataFrame pandas 中添加日期之间的天数列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22132525/
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
Add column with number of days between dates in DataFrame pandas
提问by Jase Villam
I want to subtract dates in 'A' from dates in 'B' and add a new column with the difference.
我想从“B”中的日期中减去“A”中的日期并添加一个具有差异的新列。
df
A B
one 2014-01-01 2014-02-28
two 2014-02-03 2014-03-01
I've tried the following, but get an error when I try to include this in a for loop...
我尝试了以下操作,但是当我尝试将其包含在 for 循环中时出现错误...
import datetime
date1=df['A'][0]
date2=df['B'][0]
mdate1 = datetime.datetime.strptime(date1, "%Y-%m-%d").date()
rdate1 = datetime.datetime.strptime(date2, "%Y-%m-%d").date()
delta = (mdate1 - rdate1).days
print delta
What should I do?
我该怎么办?
采纳答案by Andy Hayden
Assuming these were datetime columns (if they're not apply to_datetime) you can just subtract them:
假设这些是日期时间列(如果它们不适用to_datetime),您可以减去它们:
df['A'] = pd.to_datetime(df['A'])
df['B'] = pd.to_datetime(df['B'])
In [11]: df.dtypes # if already datetime64 you don't need to use to_datetime
Out[11]:
A datetime64[ns]
B datetime64[ns]
dtype: object
In [12]: df['A'] - df['B']
Out[12]:
one -58 days
two -26 days
dtype: timedelta64[ns]
In [13]: df['C'] = df['A'] - df['B']
In [14]: df
Out[14]:
A B C
one 2014-01-01 2014-02-28 -58 days
two 2014-02-03 2014-03-01 -26 days
Note: ensure you're using a new of pandas (e.g. 0.13.1), this may not work in older versions.
注意:确保您使用的是新的 Pandas(例如 0.13.1),这可能不适用于旧版本。
回答by A.Kot
A list comprehension is your best bet for the most Pythonic (and fastest) way to do this:
列表理解是最Pythonic(和最快)的方式来做到这一点的最佳选择:
[int(i.days) for i in (df.B - df.A)]
- i will return the timedelta(e.g. '-58 days')
- i.days will return this value as a long integer value(e.g. -58L)
- int(i.days) will give you the -58 you seek.
- 我将返回时间增量(例如“-58 天”)
- i.days 将此值作为长整数值返回(例如 -58L)
- int(i.days) 会给你你想要的 -58。
If your columns aren't in datetime format. The shorter syntax would be: df.A = pd.to_datetime(df.A)
如果您的列不是日期时间格式。较短的语法是:df.A = pd.to_datetime(df.A)
回答by Tom
How about this:
这个怎么样:
times['days_since'] = max(list(df.index.values))
times['days_since'] = times['days_since'] - times['months']
times
回答by Ricky McMaster
To remove the 'days' text element, you can also make use of the dt() accessor for series: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.html
要删除“天”文本元素,您还可以使用系列的 dt() 访问器:https: //pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.html
So,
所以,
df[['A','B']] = df[['A','B']].apply(pd.to_datetime) #if conversion required
df['C'] = (df['B'] - df['A']).dt.days
which returns:
返回:
A B C
one 2014-01-01 2014-02-28 58
two 2014-02-03 2014-03-01 26

