【问题标题】:Pandas time difference calculation errorPandas时差计算错误
【发布时间】:2018-07-02 23:28:34
【问题描述】:

我的数据框中有两个时间列:称为 date1 和 date2。 据我一直认为,两者都是 date_time 格式。但是,我现在必须计算两者之间的天数差异,但它不起作用。

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

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

如您所见,date1 的月份计算不正确! 最后的操作,不起作用的是:

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

导致以下错误:

incompatible type [object] for a datetime/timedelta operation

我一开始以为可能是date2的原因,于是试了一下:

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

导致:

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

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

【问题讨论】:

  • 您阅读时 date1 和 date2 是否都在 date_time 中?还是您使用 unit='m' 将它们转换为 date_time ?
  • date2 仍然是一列字符串日期。在执行任何操作之前,您应该首先将它们转换为日期时间对象,然后一旦正确完成,您可以使用 df.col_name.dt.month 获得月份 我不明白为什么您要从 date2 中减去一个数字并使用秒以您的第一个表格的格式。

标签: pandas datetime


【解决方案1】:

使用带有days 属性的.dt 访问器:

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

【讨论】:

  • 这个答案对我来说很好,但请问为什么month1仍然无法正确显示?
  • 我认为会重新定义 df['month1'] = pd.to_datetime(df['date1']).dt.month 并且与 df['month2'] 一样明智。您使用 pd.DatetimeIndex 有点不合常规。但是,测试它似乎你的逻辑应该工作。不知道为什么您返回的月份不正确。
猜你喜欢
  • 2018-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多