只选择在特定时间出现的行 [英] Select only rows that occur at specific time

查看:48
本文介绍了只选择在特定时间出现的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经读过C.csv,并且datetime列是object类型.

I have read in C.csv and the datetime column is a object type.

无论日期如何,我想获取其中包含23:45:00的每一行.我想将datetime作为索引,并且我想将datetime索引转换为datetime64 [ns].我相信pandas是为这种事情而设计的,但是我却把索引和数据类型混在一起了.

I want to get every row that has 23:45:00 in it, regardless of date. I would like to have datetime as index and i would like to convert datetime index to datetime64[ns]. I believe pandas is designed for this sort of thing but I'm getting my indexes and data-types mixed up.

    import datetime as dt
    import pandas as pd
    df = pd.read_csv('C.csv', index_col = 'datetime', parse_dates=['datetime'])

数据框:

                     C      H      L      O  OI  V    WAP
datetime                                                     
2017-04-22 09:23:00  39.48  39.48  39.48  39.48   0  0  39.48
2017-04-22 09:24:00  39.48  39.48  39.48  39.48   0  0  39.48
2017-04-22 09:25:00  39.48  39.48  39.48  39.48   0  0  39.48
2017-04-22 09:26:00  39.44  39.44  39.44  39.44   1  4  39.44
2017-04-22 09:27:00  39.48  39.48  39.48  39.48   3  2  39.48

推荐答案

print(df)
              datetime      C      H      L      O  OI  V    WAP
0  2017-04-22 09:23:00  39.48  39.48  39.48  39.48   0  0  39.48
1  2017-04-22 09:24:00  39.48  39.48  39.48  39.48   0  0  39.48
2  2017-04-22 09:25:00  39.48  39.48  39.48  39.48   0  0  39.48
3  2017-04-22 09:26:00  39.44  39.44  39.44  39.44   1  4  39.44
4  2017-04-22 09:27:00  39.48  39.48  39.48  39.48   3  2  39.48
5  2017-04-23 09:25:00  39.48  39.48  39.48  39.48   3  2  39.48

datetime创建索引,并将其转换为日期时间dtype:

Make datetime an index, and convert to datetime dtype:

df.set_index('datetime', inplace=True)
df.index = pd.to_datetime(df.index)

print(df.index.dtype)
dtype('<M8[ns]')

现在将匹配时间戳记设置为所需时间,并按匹配条件进行过滤:

Now set matching timestamp to desired time and filter by matches:

match_timestamp = "09:25:00"
df.loc[df.index.strftime("%H:%M:%S") == match_timestamp]

                         C      H      L      O  OI  V    WAP
datetime                                                     
2017-04-22 09:25:00  39.48  39.48  39.48  39.48   0  0  39.48
2017-04-23 09:25:00  39.48  39.48  39.48  39.48   3  2  39.48

(时间戳23:45:00未包含在示例数据中,但是为了匹配这次,只需调整match_timestamp.)

(The timestamp 23:45:00 was not included in your example data, but to match on this time instead, just adjust match_timestamp.)

这篇关于只选择在特定时间出现的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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