从pandas python中列中的日期减去索引日期

2024-04-18 16:51:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个像这样的数据框-也就是说,我有一个日期索引和一列日期。我只想从列中的日期中减去索引日期,然后将差异放入另一列。然而,我似乎可以找到如何在计算中使用指数。在

              Code   FinishDate
1990-01-01    XYZ    1999-02-14
1990-01-02    ABC    1997-01-27

Tags: 数据code差异指数abcxyzfinishdate
2条回答

如果添加日期类型为http://prntscr.com/3f4seo的字段

那么根据我的示例查询是

更新productsdif_days=DATEDIFF(date1date2)。在

希望这对你有帮助

谢谢

这是可行的,但会引发一个警告:

In [168]:

df['DateDiff'] = df.FinishDate-df.index
df
C:\WinPython-64bit-3.3.3.2\python-3.3.3.amd64\lib\site-packages\pandas\core\format.py:1851: DeprecationWarning: Implicitly casting between incompatible kinds. In a future numpy release, this will raise an error. Use casting="unsafe" if this is intentional.
  elif format_short and x == 0:
C:\WinPython-64bit-3.3.3.2\python-3.3.3.amd64\lib\site-packages\pandas\core\format.py:1851: DeprecationWarning: Implicitly casting between incompatible kinds. In a future numpy release, this will raise an error. Use casting="unsafe" if this is intentional.
  elif format_short and x == 0:
Out[168]:
           Code FinishDate  DateDiff
1990-01-01  XYZ 1999-02-14 3331 days
1990-01-02  ABC 1997-01-27 2582 days

[2 rows x 3 columns]

您必须确保索引和FinishDate都是日期时间而不是字符串,要进行转换,只需使用pd.to_datetime()

编辑

要将字符串转换为datetimes,只需执行以下操作:

^{pr2}$

我不知道是否两者都需要,但这是有效的

相关问题 更多 >