在数据框中将Pandas系列转换为DateTime

在数据框中将Pandas系列转换为DateTime

本文介绍了在数据框中将Pandas系列转换为DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的Pandas DataFrame

I have a Pandas DataFrame as below

        ReviewID       ID      Type               TimeReviewed
205     76032930  51936827  ReportID 2015-01-15 00:05:27.513000
232     76032930  51936854  ReportID 2015-01-15 00:06:46.703000
233     76032930  51936855  ReportID 2015-01-15 00:06:56.707000
413     76032930  51937035  ReportID 2015-01-15 00:14:24.957000
565     76032930  51937188  ReportID 2015-01-15 00:23:07.220000

>>> type(df)
<class 'pandas.core.frame.DataFrame'>

TimeReviewed是系列类型

TimeReviewed is a series type

>>> type(df.TimeReviewed)
<class 'pandas.core.series.Series'>

我已经在下面尝试过,但是它仍然没有更改系列类型

I've tried below, but it still doesn't change the Series type

import pandas as pd
review = pd.to_datetime(pd.Series(df.TimeReviewed))
>>> type(review)
<class 'pandas.core.series.Series'>

如何将df.TimeReviewed更改为DateTime类型并分别拉出年,月,日,时,分,秒?我是python的新手,感谢您的帮助.

How can I change the df.TimeReviewed to DateTime type and pull out year, month, day, hour, min, sec separately?I'm kinda new to python, thanks for your help.

推荐答案

您不能:根据定义,DataFrame列为Series.也就是说,如果将dtype(所有元素的类型)设为类似日期时间,则可以通过.dt访问器():

You can't: DataFrame columns are Series, by definition. That said, if you make the dtype (the type of all the elements) datetime-like, then you can access the quantities you want via the .dt accessor (docs):

>>> df["TimeReviewed"] = pd.to_datetime(df["TimeReviewed"])
>>> df["TimeReviewed"]
205  76032930   2015-01-24 00:05:27.513000
232  76032930   2015-01-24 00:06:46.703000
233  76032930   2015-01-24 00:06:56.707000
413  76032930   2015-01-24 00:14:24.957000
565  76032930   2015-01-24 00:23:07.220000
Name: TimeReviewed, dtype: datetime64[ns]
>>> df["TimeReviewed"].dt
<pandas.tseries.common.DatetimeProperties object at 0xb10da60c>
>>> df["TimeReviewed"].dt.year
205  76032930    2015
232  76032930    2015
233  76032930    2015
413  76032930    2015
565  76032930    2015
dtype: int64
>>> df["TimeReviewed"].dt.month
205  76032930    1
232  76032930    1
233  76032930    1
413  76032930    1
565  76032930    1
dtype: int64
>>> df["TimeReviewed"].dt.minute
205  76032930     5
232  76032930     6
233  76032930     6
413  76032930    14
565  76032930    23
dtype: int64


如果您使用的是较旧版本的pandas,则始终可以手动访问各种元素(同样,将其转换为日期时间类型的Series之后).它会变慢,但是有时候这不是问题:


If you're stuck using an older version of pandas, you can always access the various elements manually (again, after converting it to a datetime-dtyped Series). It'll be slower, but sometimes that isn't an issue:

>>> df["TimeReviewed"].apply(lambda x: x.year)
205  76032930    2015
232  76032930    2015
233  76032930    2015
413  76032930    2015
565  76032930    2015
Name: TimeReviewed, dtype: int64

这篇关于在数据框中将Pandas系列转换为DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 01:58