问题:在DataFrame Pandas中添加带有日期之间的天数的列

我想从“ B”中的日期中减去“ A”中的日期,并添加一个具有差异的新列。

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

我尝试了以下操作,但是在尝试将其包含在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

我该怎么办?

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

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

What should I do?


回答 0

假设这些是datetime列(如果不适用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

注意:请确保您使用的是新熊猫(例如0.13.1),这可能在较旧的版本中不起作用。

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

Note: ensure you’re using a new of pandas (e.g. 0.13.1), this may not work in older versions.


回答 1

要删除“天”文本元素,您还可以使用系列的dt()访问器:https : //pandas.pydata.org/pandas-docs/stable/generation/pandas.Series.dt.html

所以,

df[['A','B']] = df[['A','B']].apply(pd.to_datetime) #if conversion required
df['C'] = (df['B'] - df['A']).dt.days

返回:

             A          B   C
one 2014-01-01 2014-02-28  58
two 2014-02-03 2014-03-01  26

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

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

回答 2

列表理解是最Python(最快捷)的方式的最佳选择:

[int(i.days) for i in (df.B - df.A)]
  1. 我将返回timedelta(例如“ -58天”)
  2. i.days将以长整数值(例如-58L)返回此值
  3. int(i.days)将为您提供-58。

如果您的列不是日期时间格式。较短的语法为:df.A = pd.to_datetime(df.A)

A list comprehension is your best bet for the most Pythonic (and fastest) way to do this:

[int(i.days) for i in (df.B - df.A)]
  1. i will return the timedelta(e.g. ‘-58 days’)
  2. i.days will return this value as a long integer value(e.g. -58L)
  3. int(i.days) will give you the -58 you seek.

If your columns aren’t in datetime format. The shorter syntax would be: df.A = pd.to_datetime(df.A)


回答 3

这个怎么样:

times['days_since'] = max(list(df.index.values))  
times['days_since'] = times['days_since'] - times['months']  
times

How about this:

times['days_since'] = max(list(df.index.values))  
times['days_since'] = times['days_since'] - times['months']  
times

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。