Python 将序列而不是整数传递到偏移量

Python 将序列而不是整数传递到偏移量,python,pandas,Python,Pandas,我有一个带有日期和数字的数据帧(df)。我想把号码加到日期上。如何使用pd.offset()将df['additional_days']系列添加到df['start_date']系列?有更好的方法吗 开始日期附加天数 2018-03-29 360 2018-07-31 0 2018-11-01 360 2016-11-03 720 2018-12-04 480 我尝试时出错了 df['start_date'] + pd.offsets.Day(df['additional_days']) 这

我有一个带有日期和数字的数据帧(df)。我想把号码加到日期上。如何使用pd.offset()将df['additional_days']系列添加到df['start_date']系列?有更好的方法吗

开始日期附加天数

2018-03-29 360

2018-07-31 0

2018-11-01 360

2016-11-03 720

2018-12-04 480

我尝试时出错了

df['start_date'] + pd.offsets.Day(df['additional_days']) 
这里是错误

TypeError                                 Traceback (most recent call last)
pandas/_libs/tslibs/offsets.pyx in pandas._libs.tslibs.offsets._BaseOffset._validate_n()

/opt/conda/lib/python3.6/site-packages/pandas/core/series.py in wrapper(self)
    117         raise TypeError("cannot convert the series to "
--> 118                         "{0}".format(str(converter)))
    119 

TypeError: cannot convert the series to <class 'int'>

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-76-03920804db29> in <module>
----> 1 df_test['start_date'] + pd.offsets.Day(df_test['additional_days'])

/opt/conda/lib/python3.6/site-packages/pandas/tseries/offsets.py in __init__(self, n, normalize)
   2219     def __init__(self, n=1, normalize=False):
   2220         # TODO: do Tick classes with normalize=True make sense?
-> 2221         self.n = self._validate_n(n)
   2222         self.normalize = normalize
   2223 

pandas/_libs/tslibs/offsets.pyx in pandas._libs.tslibs.offsets._BaseOffset._validate_n()

TypeError: `n` argument must be an integer, got <class 'pandas.core.series.Series'>
TypeError回溯(最近一次调用)
pandas/_libs/tslibs/offset.pyx在pandas中。_libs.tslibs.offset._BaseOffset._validate_n()
/包装器中的opt/conda/lib/python3.6/site-packages/pandas/core/series.py(self)
117 raise TypeError(“无法将序列转换为”
-->118“{0}”。格式(str(转换器)))
119
TypeError:无法将序列转换为
在处理上述异常期间,发生了另一个异常:
TypeError回溯(最近一次调用上次)
在里面
---->1 df_测试[‘开始_日期’]+pd.offset.Day(df_测试[‘额外_天])
/opt/conda/lib/python3.6/site-packages/pandas/tseries/offset.py in_u__________(self,n,normalize)
2219定义初始化(self,n=1,normalize=False):
2220#TODO:用normalize=True勾选类有意义吗?
->2221 self.n=self.\u验证\u n(n)
2222自正常化=正常化
2223
pandas/_libs/tslibs/offset.pyx在pandas中。_libs.tslibs.offset._BaseOffset._validate_n()
TypeError:`n`参数必须是整数,已获取

使用
pd.to\u timedelta

import pandas as pd
#df['start_date'] = pd.to_datetime(df.start_date)

df['start_date'] + pd.to_timedelta(df.additional_days, unit='d')

#0   2019-03-24
#1   2018-07-31
#2   2019-10-27
#3   2018-10-24
#4   2020-03-28
#dtype: datetime64[ns]

可能还有其他原因,但我发现当需要特定的逻辑来添加一个恒定的、定义不太明确的时间段时,
pd.offset
通常是最好的选择。一天的定义非常明确,因此对于日期+X天的含义,从来没有任何含糊不清的地方。相反,像
1个月
之类的内容没有很好的定义,因此
pd.offset.DateOffset
使您能够根据逻辑使用一些有用的逻辑来定义它