python - 将系列而不是整数传递给 Pandas 偏移量

标签 python pandas

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

start_date additional_days

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'>

最佳答案

使用pd.to_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]

关于python - 将系列而不是整数传递给 Pandas 偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54581339/

相关文章:

pandas - 将 pandas 数据帧转换为稀疏矩阵

python - pandas 选择数据框中有条件的特定列与另一个条件导致串联

python - 使用 rank (Python) 对字符串的频率分布进行排序

python - Kivy:是否可以用类级别(而不是实例)属性触发事件?

python - 从 pandas 时间戳中删除日期部分的最快方法

python - Pandas 0.19.0explode() 解决方法

Python:转换深层嵌套字典或数组中的类型

python - Ruby HMAC-SHA 不同于 Python

Python TCP 端口扫描器

python - 在 Python 中将自相关计算为滞后函数