我已经读入了C.csv
,并且datetime
列是一个object
类型。
我想获取每一行中包含23:45:00
的内容,而不管日期如何。我想有datetime
作为索引,我想将datetime
索引转换为datetime64ns。我相信pandas就是为这类事情而设计的,但是我把索引和数据类型搞混了。
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
发布于 2017-05-15 08:11:10
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
作为索引,并转换为datetime dtype
df.set_index('datetime', inplace=True)
df.index = pd.to_datetime(df.index)
print(df.index.dtype)
dtype('<M8[ns]')
现在将匹配的时间戳设置为所需的时间,并按匹配进行过滤:
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
即可。)
https://stackoverflow.com/questions/43969877
复制相似问题