简体   繁体   English

从 DateTime Pandas 系列中提取小时数

[英]Extract Hours from DateTime Pandas Series

I have a Pandas Series of DateTime我有一个日期时间的 Pandas 系列

>> s
0             NaT
3        23:00:42
26            NaT
53       23:58:58
89       01:06:27
           ...   
20215         NaT
20217         NaT
20239    23:28:38
20246         NaT
20270         NaT

I first drop the NaT using:我首先使用以下方法删除 NaT:

s.dropna()
3        23:00:42
53       23:58:58
89       01:06:27
97       01:18:36
195      05:43:07
           ...   
20132    19:21:20
20141    20:08:01
20152    20:21:01
20199    22:25:50
20239    23:28:38

Now I try to get the hours from the series but not sure how to do that.现在我尝试从系列中获取时间,但不知道如何做到这一点。

Use if s is Series convert values to datetimes and then extract hours:使用 if s is Series将值转换为日期时间,然后提取小时数:

s = pd.to_datetime(s.astype(str)).dt.hour

Or get first 2 values and convert to floats:或获取前 2 个值并转换为浮点数:

s = s.str[:2].astype(float)

If working with column:如果使用列:

df['hour'] = pd.to_datetime(df['col'].astype(str)).dt.hour

Or:或者:

df['hour'] = df['col'].str[:2].astype(float)

Try this:尝试这个:

s['hour'] = s['time'].apply(lambda x: x[3:5])

There are many approaches.有很多方法。 I would do it like this:我会这样做:

s = pd.Series(pd.to_datetime(x).hour for x in s) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM