【问题标题】:How to change a column containing dates with dtype:object into a datetime and apply a difference with another datetime?如何将包含 dtype:object 日期的列更改为日期时间并应用与另一个日期时间的差异?
【发布时间】:2020-04-30 01:22:09
【问题描述】:

我有以下数据:

    fip_code           npi                             start_date                                                                                                                                   
     0          1      gathering_size_10_0             3/28/2020                                                                                                                                   
     1          1      gathering_size_25_to_11         3/19/2020                                                                                                                                   
     2          1      non-essential_services_closure  3/28/2020   
     .          .                     .                 
     .          .                     .                 
     .          .                     .                 

我想将 start_date 列的每个值转换为日期时间对象,例如 x,然后给定日期时间对象 y = 2020-03-12 00:00:00,将 start_date 列中的值替换为 x-y

这是用于生成数据帧的代码:

    import pandas as pd  
    import numpy as np 
    from datetime import datetime 
    from dateutil import parser

    url_npi = 'https://raw.githubusercontent.com/Keystone-Strategy/covid19-interventiondata/master/complete_npis_raw_policies.csv'
    df = pd.read_csv(url_npi, error_bad_lines=False)
    df = df[['fip_code','npi','start_date']]

【问题讨论】:

    标签: python datetime lambda apply


    【解决方案1】:

    好的,我想出了这个:

    df['start_date'] = pd.to_datetime(df['start_date'],infer_datetime_format=True,errors="coerce")
    base_str = "3/1/2020"; print("\n\n base date: ",base_str)
    end_str = "4/29/2020"; print("\n\n end date: ",end_str)
    base = pd.to_datetime(base_str)
    end = pd.to_datetime(end_str)
    df_npi['days_in_effect'] = df_npi.apply(lambda row: (end - row['start_date']).days, axis=1)
    df_npi['days_from_base'] = df_npi.apply(lambda row: (row['start_date'] - base).days, axis=1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多