简体   繁体   中英

Keyerror when searching for a date PRIOR to Date TIme in python pandas dataframe using getloc ffill

I have the following data frame. I want to get the nearest date using get_loc ffill parameter as mentioned in the code snippet. DataFrame:

Date Time,Close,High,Low,Open,Volume
2020-01-02 22:45:00,326.75,329.3,326.5,329.3,0.0
2020-01-02 22:50:00,328.0606,330.0708,325.6666,326.7106,9178.0
2020-01-02 22:55:00,327.4,328.3,327.4,328.05,1035.0
...
2020-02-07 04:50:00,372.05,375.0,372.0,373.0,4936.0
2020-02-07 04:55:00,372.1156,373.3588,370.3559,372.3656,7548.0

Code Snippet

df_colname = 'Date Time'
pandas_datetime_colname = 'Pandas Date Time'
df[pandas_datetime_colname] = pd.to_datetime(df[df_colname])
df.set_index(pandas_datetime_colname, inplace=True)
dt = pd.to_datetime(inputdatetime)
idx = df.index.get_loc(dt, 'ffill')
print("Date Time: " + str(inputdatetime) + " :idx " + str(idx))
df.reset_index(inplace=True)

This returns the correct date 2020-01-02 22:45:00 when I provide date as 2020-02-02 22:50:00 but when I give a date PRIOR to the first date, I get a keyerror KeyError: Timestamp('2019-12-20 22:45:00') I also don't get an error when I give a date AFTER the last date in the dataframe

I looked through the documents but could not find why I get an error only for dates PRIOR . I was hoping to get some kind of a None object

From the docs :

ffill: find the PREVIOUS index value if no exact match.

Giving a datetime with no prior datetimes in the index, will result in an error due to it giving the closest match in the PREVIOUS index value. Since there is no such index value, it throws an error.

I believe what you're looking for is the nearest argument, instead of ffill :

nearest: use the NEAREST index value if no exact match. Tied distances are broken by preferring the larger index value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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