【问题标题】:Calculating difference in years for the whole dataframe计算整个数据框的年差
【发布时间】:2021-10-10 12:37:08
【问题描述】:

我有一个包含两个日期的数据框,我想添加一个新列,该列是两者之间的年差。

birthDate  |  created_at                         |  diff_in_years
2000-10    |  2019-06-17 13:15:04.598799+00:00   |

我编写了以下代码来计算差异。因为我不知道birthDate 的确切日期,所以我手动将两者都设置为 1。它适用于一排。

def convert_to_datetime(str):
    x = int(str[0:4])
    y = int(str[5:7])
    z = 1
    return datetime.datetime(x,y,z)


start_date = "2000-10"
start_date = convert_to_datetime(start_date)
end_date = "2019-06-17 13:15:04.598799+00:00"
end_date = convert_to_datetime(end_date)
diff = relativedelta(end_date,start_date)

但问题是如何为整个数据帧运行此计算?我已经尝试过apply 功能,但不起作用。我没有正确使用它。

 data.apply(relativedelta(convert_to_datetime(data["created_at"]),convert_to_datetime(data["birthDate"]), axis=1))

【问题讨论】:

    标签: python pandas dataframe datetime timedelta


    【解决方案1】:

    尝试以下,尝试使用 pandas 内置函数进行日期时间转换:

    df['birthDate'] = pd.to_datetime(df['birthDate'])
    df['created_at'] = pd.to_datetime(df['created_at'])
    #from here you can just simply substract
    
    df['difference'] = df['created_at'] - df['birthDate'] 
    #note that this will give you the difference in days, try to divide by 365 or something like that
    
    

    【讨论】:

    • 谢谢,这很有意义。我遇到了一些时区和其他不一致的问题,但现在可以了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 2012-07-30
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多