【问题标题】:Python: Add Weeks to Date from dfPython:从 df 添加周到日期
【发布时间】:2021-12-02 10:17:55
【问题描述】:

如何将两个 df 列加在一起(日期 + 周):

这对我有用:

df['Date'] = pd.to_datetime(startDate, format='%Y-%m-%d') + datetime.timedelta(weeks = 3)

但是当我尝试从列中添加周数时,我收到一个类型错误:timedelta 周组件的类型不受支持:系列

df['Date'] = pd.to_datetime(startDate, format='%Y-%m-%d') + datetime.timedelta(weeks = df['Duration (weeks)'])

感谢您的帮助!

【问题讨论】:

  • 也许你可以增加 21 天?
  • 我认为这与我使用列的事实有关,因为周 = 3 可以正常工作。只有当我尝试将 3 替换为 df 中的列时,我才会收到错误消息。
  • Pandas 有一个 to_timedelta 函数,您可以使用它来转换整个第二列,然后再将其添加到另一列。

标签: python dataframe python-datetime


【解决方案1】:

您可以使用 pandas to_timelta 函数将周数列转换为时间增量,如下所示:

import pandas as pd
import numpy as np

# create a DataFrame with a `date` column
df = pd.DataFrame(
    pd.date_range(start='1/1/2018', end='1/08/2018'),
    columns=["date"]
)

# add a column `weeks` with a random number of weeks
df['weeks'] = np.random.randint(1, 6, df.shape[0])

# use `pd.to_timedelta` to transform the number of weeks column to a timedelta
# and add it to the `date` column 
df["new_date"] = df["date"] + pd.to_timedelta(df["weeks"], unit="W")

df.head()

    date       weeks    new_date
0   2018-01-01  5   2018-02-05
1   2018-01-02  2   2018-01-16
2   2018-01-03  2   2018-01-17
3   2018-01-04  4   2018-02-01
4   2018-01-05  3   2018-01-26

【讨论】:

    猜你喜欢
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    • 2012-08-06
    相关资源
    最近更新 更多