pandas 如何在熊猫中减去天数后获取日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40104946/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:14:14  来源:igfitidea点击:

How to get date after subtracting days in pandas

pythonpandas

提问by rey

I have a dataframe:

我有一个数据框:

In [15]: df
Out[15]: 
        date  day
0 2015-10-10   23
1 2015-12-19    9
2 2016-03-05   34
3 2016-09-17   23
4 2016-04-30    2

I want to subtract the number of days from the date and create a new column.

我想从日期中减去天数并创建一个新列。

In [16]: df.dtypes
Out[16]: 
date    datetime64[ns]
day              int64

Desired output something like:

所需的输出类似于:

In [15]: df
Out[15]: 
        date  day date1
0 2015-10-10   23 2015-09-17
1 2015-12-19    9 2015-12-10
2 2016-03-05   34 2016-01-29
3 2016-09-17   23 2016-08-25
4 2016-04-30    2 2016-04-28

I tried but this does not work:

我试过了,但这不起作用:

df['date1']=df['date']+pd.Timedelta(df['date'].dt.day-df['day'])

it throws error :

它抛出错误:

TypeError: unsupported type for timedelta days component: Series

类型错误:timedelta 天组件不支持的类型:系列

回答by jezrael

You can use to_timedelta:

您可以使用to_timedelta

df['date1'] = df['date'] -  pd.to_timedelta(df['day'], unit='d')

print (df)
        date  day      date1
0 2015-10-10   23 2015-09-17
1 2015-12-19    9 2015-12-10
2 2016-03-05   34 2016-01-31
3 2016-09-17   23 2016-08-25
4 2016-04-30    2 2016-04-28

If need Timedeltause apply, but it is slowier:

如果需要Timedelta使用apply,但速度较慢:

df['date1'] = df['date'] -  df.day.apply(lambda x: pd.Timedelta(x, unit='D'))

print (df)
        date  day      date1
0 2015-10-10   23 2015-09-17
1 2015-12-19    9 2015-12-10
2 2016-03-05   34 2016-01-31
3 2016-09-17   23 2016-08-25
4 2016-04-30    2 2016-04-28

Timings:

时间

#[5000 rows x 2 columns]
df = pd.concat([df]*1000).reset_index(drop=True)

In [252]: %timeit df['date'] -  df.day.apply(lambda x: pd.Timedelta(x, unit='D'))
10 loops, best of 3: 45.3 ms per loop

In [253]: %timeit df['date'] -  pd.to_timedelta(df['day'], unit='d')
1000 loops, best of 3: 1.71 ms per loop

回答by sachin saxena

import dateutil.relativedelta
def calculate diff(v):
    return v['date'] - dateutil.relativedelta.relativedelta(day=v['day'])
df['date1']=df.apply(calculate_diff, axis=1)

given that v['date'] is datetime object

鉴于 v['date'] 是日期时间对象