我有一个Pandas DataFrame,如下所示
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是一个系列类型
>>> type(df.TimeReviewed)
<class 'pandas.core.series.Series'>
我在下面试过了,但它仍然没有改变系列类型
import pandas as pd
review = pd.to_datetime(pd.Series(df.TimeReviewed))
>>> type(review)
<class 'pandas.core.series.Series'>
如何将df.TimeReviewed更改为DateTime类型并分别提取年,月,日,小时,分钟? 感谢你的帮助,我对python有点新意。
答案 0 :(得分:45)
根据定义,您不能DataFrame
列Series
。也就是说,如果您使dtype
(所有元素的类型)与datetime类似,那么您可以通过.dt
访问者(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
,您可以随时手动访问各种元素(再次将其转换为datetime-dtyped系列)。它会慢一点,但有时这不是问题:
>>> 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
答案 1 :(得分:1)
一些方便的脚本:
hour = df['assess_time'].dt.hour.values[0]
答案 2 :(得分:0)
df=pd.read_csv("filename.csv" , parse_dates=["<column name>"])
type(df.<column name>)
示例:如果您要将最初是字符串的day转换为Pandas中的时间戳记
df=pd.read_csv("weather_data2.csv" , parse_dates=["day"])
type(df.day)
输出将为pandas.tslib.Timestamp