简体   繁体   English

pandas dataframe 中的索引时间戳问题

[英]Issue with indexing timestamp in pandas dataframe

I have a pandas dataframe which reads from a csv file and has a timestamp column.我有一个 pandas dataframe 它从 csv 文件中读取并具有timestamp列。 I am trying to get the rows that were in the last 3 hours.我正在尝试获取过去 3 小时内的行。 So far I have:到目前为止,我有:

 df_trade = pd.read_csv("log.csv")
 df_ma.set_index('timestamp')
 start = format_time()
 end = start - pd.Timedelta(hours=3)
 df_ma = df_ma[end:]

This is my helper function:这是我的助手 function:

def format_time():
    t = datetime.now()
    s = t.strftime('%Y-%m-%d %H:%M:%S')
    return pd.to_datetime(s)

However, I get this error when I try to do slicing:但是,当我尝试进行切片时出现此错误:

TypeError: cannot do slice indexing on RangeIndex with these indexers [2021-06-01 07:07:53] of type Timestamp

How can I resolve this issue我该如何解决这个问题

You have to change your last line:您必须更改最后一行:

df_ma = df_ma[end:]

become变得

df_ma = df_ma.loc[df_ma.index > end]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM