我已经读过C.csv
和datetime
列是一个object
type.
我想得到每一行23:45:00
无论日期如何,都在其中。我想拥有datetime
作为索引,我想转换datetime
datetime64[ns] 的索引。我相信 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
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
Make 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
.)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)