在DataFrame Pandas中添加带有日期之间的天数的列 [英] Add column with number of days between dates in DataFrame pandas

查看:330
本文介绍了在DataFrame Pandas中添加带有日期之间的天数的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从"B"中的日期中减去"A"中的日期,并添加具有差异的新列.

I want to subtract dates in 'A' from dates in 'B' and add a new column with the difference.

df
          A        B
one 2014-01-01  2014-02-28 
two 2014-02-03  2014-03-01

我尝试了以下操作,但是在尝试将其包含在for循环中时出现错误...

I've tried the following, but get an error when I try to include this in a for loop...

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

我该怎么办?

推荐答案

假设这些是日期时间列(如果它们不适用to_datetime),则可以减去它们:

Assuming these were datetime columns (if they're not apply to_datetime) you can just subtract them:

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

注意:请确保您使用的是新的熊猫(例如0.13.1),在旧版本中可能无法使用.

这篇关于在DataFrame Pandas中添加带有日期之间的天数的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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