在熊猫数据框中将相对时间更改为实际日期

SP

我目前有一个通过抓取Google新闻标题创建的数据框。我的专栏之一是“时间”,它是指文章发表的时间。

不幸的是,对于最近的文章,google新闻使用的是“相对”日期,例如6小时前或1天前,而不是2017年11月1日。

我确实想将这些相对日期转换为与其他条目一致(例如,他们也说2017年11月12日),但是我什至不知道从哪里开始。

我的想法是可能要创建一个代表今天日期的变量,然后在数据框中进行某种搜索以查找与我的格式不匹配的内容,然后将这些相对时间与当前日期相减。我还必须对“小时前”的东西进行过滤,使它们等于当前日期。

我并不是真的想要一个解决方案,而是想要阅读的一般概念来尝试解决这个问题。我应该尝试使用numpy吗?

一些行的示例:

     Publication    Time    Headline
0   The San Diego Union-Tribune     6 hours ago     I am not opposed to new therapeutic modalities...
1   Devon Live  13 hours ago    If you're looking for a bargain this Christmas...
15  ABS-CBN News    1 day ago   Now, Thirdy has a chance to do something that ...
26  New York Times  Nov 2, 2017     Shepherds lead their sheep through the centre ...
andrew_reece

您的方法应该可行。使用熊猫Timedelta从当前日期中减去相对日期。

例如,给定您的样本数据为:

Publication;Time;Headline
The San Diego Union-Tribune;6 hours ago;I am not opposed to new therapeutic modalities
Devon Live;13 hours ago;If you're looking for a bargain this Christmas
ABS-CBN News;1 day ago;Now, Thirdy has a chance to do something that
New York Times;Nov 2, 2017;Shepherds lead their sheep through the centre

从剪贴板中读取数据(尽管您可以轻松地用read_csv()或其他文件格式替换数据):

import pandas as pd
from datetime import datetime

df = pd.read_clipboard(sep=";")

对于已经采用日期格式的日期,Pandas非常聪明,可以使用to_datetime()以下命令进行转换

absolute_date = pd.to_datetime(df.Time, errors="coerce")

absolute_date
0          NaT
1          NaT
2          NaT
3   2017-11-02
Name: Time, dtype: datetime64[ns]

对于相对日期,一旦我们删除“ ago”部分,它们的格式基本上就可以正确转换为pd.Timedelta

relative_date = (datetime.today() - 
                 df.Time.str.extract("(.*) ago", expand=False).apply(pd.Timedelta))

relative_date
0   2017-11-11 17:05:54.143548
1   2017-11-11 10:05:54.143548
2   2017-11-10 23:05:54.143548
3                          NaT
Name: Time, dtype: datetime64[ns]

现在,NaN从绝对和相对的每个集合中填充各自的值(combine_first()通过Jezrael的答案更新为use ):

date = relative_date.combine_first(absolute_date)

relative_date
0   2017-11-11 17:06:29.658925
1   2017-11-11 10:06:29.658925
2   2017-11-10 23:06:29.658925
3   2017-11-02 00:00:00.000000
Name: Time, dtype: datetime64[ns]

最后,仅从datetime中取出日期:

date.dt.date
0    2017-11-11
1    2017-11-11
2    2017-11-10
3    2017-11-02
Name: Time, dtype: object

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章