我在 C.csv
中读过,datetime
列是 object
类型。
我想获取其中包含 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
将datetime
作为索引,并转换为datetimedtype
:
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
。)
关于python - 仅选择在特定时间发生的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43969877/