【问题标题】:How to add month column to a date column in python?如何将月份列添加到python中的日期列?
【发布时间】:2020-04-08 07:30:52
【问题描述】:
date['Maturity_date'] = data.apply(lambda data: relativedelta(months=int(data['TRM_LNTH_MO'])) + data['POL_EFF_DT'], axis=1)

也试过这个:

date['Maturity_date'] = date['POL_EFF_DT'] + date['TRM_LNTH_MO'].values.astype("timedelta64[M]")

TypeError: 'type' 对象不支持项目分配

【问题讨论】:

  • 对我来说,使用date.apply 而不是data.apply 很好。
  • 请遵循编辑指南。

标签: python pandas data-science timedelta


【解决方案1】:
import pandas as pd
import datetime

#Convert the date column to date format
date['date_format'] = pd.to_datetime(date['Maturity_date'])

#Add a month column
date['Month'] = date['date_format'].apply(lambda x: x.strftime('%b'))

【讨论】:

    【解决方案2】:

    如果您使用的是 Pandas,则可以使用名为“频率别名”的资源。开箱即用的东西:

    # For "periods": 1 (is the current date you have) and 2 the result, plus 1, by the frequency of 'M' (month).
    
    import pandas as pd
    
    _new_period = pd.date_range(_existing_date, periods=2, freq='M')
    
    

    现在您可以准确地获得所需的句点作为返回的第二个元素:

    # The index for your information is 1. Index 0 is the existing date.
    
    _new_period.strftime('%Y-%m-%d')[1]
    
    # You can format in different ways. Only Year, Month or Day. Whatever.
    
    

    Consult this link for further information

    【讨论】:

      猜你喜欢
      • 2020-05-28
      • 2015-07-31
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 2022-12-03
      • 2022-01-19
      • 2021-01-24
      相关资源
      最近更新 更多