【问题标题】:Extract Hours from DateTime Pandas Series从 DateTime Pandas 系列中提取小时数
【发布时间】:2021-05-07 13:34:23
【问题描述】:

我有一个 Pandas 系列的 DateTime

>> 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

我首先使用以下方法删除 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

现在我尝试从系列中获取小时数,但不知道该怎么做。

【问题讨论】:

  • 什么是print (s.dtype) ?
  • dtype: 对象。此外,如果我使用值访问,我会得到一个日期时间对象数组。

标签: python pandas datetime series


【解决方案1】:

如果sSeries 则使用将值转换为日期时间,然后提取小时数:

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

或者获取前 2 个值并转换为浮点数:

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

如果使用列:

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

或者:

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

【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
    【解决方案3】:

    有很多方法。我会这样做:

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

    【讨论】:

    • 嗯,它是循环的,在 pandas 中很慢,最好使用矢量化函数。
    • 好的,谢谢您的建议。会记住的。
    猜你喜欢
    • 2010-11-20
    • 2020-07-17
    • 1970-01-01
    • 2021-06-05
    • 2019-11-05
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    • 2021-09-13
    相关资源
    最近更新 更多