在pandas中从列中日期减去索引日期
我有一个数据表(DataFrame),它的样子是这样的:有一列是日期作为索引,还有一列也是日期。我想做的就是把索引中的日期减去那一列中的日期,然后把这个差值放到另一列里。但是,我找不到怎么在计算中使用这个索引。
Code FinishDate
1990-01-01 XYZ 1999-02-14
1990-01-02 ABC 1997-01-27
2 个回答
-3
如果你像这样添加日期类型的字段 http://prntscr.com/3f4seo
那么根据我的示例,查询语句是
UPDATE products
SET dif_days
= DATEDIFF( date1
, date2
).
希望这能帮到你
谢谢
0
这个方法可以用,但会有一个警告:
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]
你需要确保你的索引和结束日期都是日期时间格式,而不是字符串。如果要进行转换,可以使用 pd.to_datetime()
这个函数。
补充说明
要把字符串转换成日期时间格式,只需要这样做:
df.index = pd.to_datetime(df.index)
df.FinishDate = pd.to_datetime(df.FinishDate)
我不确定这两者是否都需要,但这个方法是有效的。