【问题标题】:Take the difference in dates in months and Average in Python以月为单位的日期差和 Python 中的平均值
【发布时间】:2021-03-03 03:19:14
【问题描述】:

我有一个数据集 df,我想从现在(2021 年 3 月 2 日)的几个月内获取日期差异,最后取其平均值

数据

A           B           C           D
3/2/2015    3/2/2016    3/2/2010    3/2/2005
3/2/2000    3/2/2010    3/2/2005    4/2/2005

想要的

A       B       C       D
72.00   60.00   132.00  192.00
252.00  132.00  192.00  193.00
162.00  96.00   162.00  192.50

在做

import datetime


f_date = date(2015, 3, 2)
l_date = date(2021, 3, 2)
delta = l_date - f_date
print(delta.days)

但是,我怎样才能实现它以在整个数据帧上工作以提供所需的输出

欢迎提出任何建议。

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    您可以使用apply + pd.to_datetime 将列ABCD 中的值解析为pandas datetime 对象,转换后从今天的日期中减去它得到包含timedelta对象的数据框,最后除以np.timedelta64(1, 'M')得到months

    out = df.apply(pd.to_datetime, errors='coerce')
    out = (pd.to_datetime('today').normalize() - out) / np.timedelta64(1, 'M')
    
    >>> out
                A           B           C           D
    0   72.050761   60.025873  132.043779  192.036797
    1  252.029816  132.043779  192.036797  191.018296
    

    为了平均使用meanaxis=0

    >>> out.mean()
    
    A    162.040288
    B     96.034826
    C    162.040288
    D    191.527547
    dtype: float64
    

    【讨论】:

      【解决方案2】:

      您可以简单地将日期时间传递给to_period('M') 并获得差异:

      df = df.applymap(lambda x: (pd.to_datetime('today').to_period('M') - x.to_period('M')).n)
      

      输出:

      A B C D
      0 72 60 132 192
      1 252 132 192 191

      【讨论】:

      • 您可以将pd.to_datetime('today').to_period('M') 作为效率变量。
      • 谢谢@RJ Adriaansen,上面写着:AttributeError: 'str' object has no attribute 'to_period'
      • 然后运行df = df.applymap(pd.to_datetime)首先将所有日期转换为日期时间对象。您会发现此解决方案会自动对月份进行四舍五入。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 2011-02-16
      • 2021-12-01
      • 2016-06-07
      相关资源
      最近更新 更多