pandas ,数据帧与datetime64列,按小时查询 [英] Pandas, dataframe with a datetime64 column, querying by hour

查看:243
本文介绍了 pandas ,数据帧与datetime64列,按小时查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫数据框 df 其中有一列由 datetime64 组成,例如

 < class'pandas.core.frame.DataFrame'> 
Int64Index:1471个条目,0到2940
数据列(共2列):
日期1471非空值
id 1471非空值
dtypes: datetime64 [ns](1),int64(1)

我想对 df 使用一天中的小时(独立于日期中的其他信息)。例如,伪代码

  df_sub = df [(HOUR(df.date)> 8)& (HOUR(df.date)<20)] 

某些功能 HOUR



我猜这个问题可以通过从 datetime64 datetime 。这可以更有效地处理吗?

解决方案

找到一个简单的解决方案。

  df ['hour'] = df.date.apply(lambda x:x.hour)

df_sub = df [(df.hour> 8)& (df.hour)< 20]






编辑:



有一个属性 dt 专门介绍来处理这个问题。查询变成:

  df_sub = df [(df.date.dt.hour> 8)
& (df.date.dt.hour <20)]


I have a pandas dataframe df which has one column constituted by datetime64, e.g.

<class 'pandas.core.frame.DataFrame'>
Int64Index: 1471 entries, 0 to 2940
Data columns (total 2 columns):
date    1471  non-null values
id      1471  non-null values
dtypes: datetime64[ns](1), int64(1)

I would like to sub-sample df using as criterion the hour of the day (independently on the other information in date). E.g., in pseudo code

df_sub = df[ (HOUR(df.date) > 8) & (HOUR(df.date) < 20) ]

for some function HOUR.

I guess the problem can be solved via a preliminary conversion from datetime64 to datetime. Can this be handled more efficiently?

解决方案

Found a simple solution.

df['hour'] = df.date.apply(lambda x : x.hour)

df_sub = df[(df.hour > 8) & (df.hour) <20]


EDIT:

There is a property dt specifically introduced to handle this problem. The query becomes:

df_sub = df[ (df.date.dt.hour > 8) 
              &  (df.date.dt.hour < 20) ]

这篇关于 pandas ,数据帧与datetime64列,按小时查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆