仅选择在pandas dataframe

时间:2017-05-14 23:50:37

标签: python pandas datetime time

我在'C.csv'中读过,'datetime'列是'对象'类型。 无论日期如何,我都希望每一行都有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

1 个答案:

答案 0 :(得分:4)

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

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。)