代码之家  ›  专栏  ›  技术社区  ›  user27074

熊猫时差计算误差

  •  0
  • user27074  · 技术社区  · 7 年前

    我的数据框架中有两个时间列:称为日期1和日期2。 就我一直认为的,两者都是日期时间格式。但是,我现在必须计算这两者之间的天数差,但这不起作用。

    我运行以下代码来分析数据:

    df['month1'] = pd.DatetimeIndex(df['date1']).month
    df['month2'] = pd.DatetimeIndex(df['date2']).month
    print(df[["date1", "date2", "month1", "month2"]].head(10))
    print(df["date1"].dtype)
    print(df["date2"].dtype)
    

    输出为:

        date1         date2     month1  month2
    0 2016-02-29   2017-01-01       1       1
    1 2016-11-08   2017-01-01       1       1
    2 2017-11-27   2009-06-01       1       6
    3 2015-03-09   2014-07-01       1       7
    4 2015-06-02   2014-07-01       1       7
    5 2015-09-18   2017-01-01       1       1
    6 2017-09-06   2017-07-01       1       7
    7 2017-04-15   2009-06-01       1       6
    8 2017-08-14   2014-07-01       1       7
    9 2017-12-06   2014-07-01       1       7
    datetime64[ns]
    object
    

    如您所见,日期1的月份计算不正确! 不起作用的最终操作是:

    df["date_diff"] = (df["date1"]-df["date2"]).astype('timedelta64[D]')
    

    导致以下错误:

    incompatible type [object] for a datetime/timedelta operation
    

    我第一次想到可能是因为约会2,所以我试着:

    df["date2_new"] = pd.to_datetime(df['date2'] - 315619200, unit = 's')
    

    导致:

     unsupported operand type(s) for -: 'str' and 'int'
    

    有人知道我需要改变什么吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Scott Boston    7 年前

    使用.dt访问器 days 属性:

    df[['date1','date2']] = df[['date1','date2']].apply(pd.to_datetime)
    df['date_diff'] = (df['date1'] - df['date2']).dt.days
    

    输出:

           date1      date2  month1  month2  date_diff
    0 2016-02-29 2017-01-01       1       1       -307
    1 2016-11-08 2017-01-01       1       1        -54
    2 2017-11-27 2009-06-01       1       6       3101
    3 2015-03-09 2014-07-01       1       7        251
    4 2015-06-02 2014-07-01       1       7        336
    5 2015-09-18 2017-01-01       1       1       -471
    6 2017-09-06 2017-07-01       1       7         67
    7 2017-04-15 2009-06-01       1       6       2875
    8 2017-08-14 2014-07-01       1       7       1140
    9 2017-12-06 2014-07-01       1       7       1254