簡體   English   中英

使用getloc ffill在python pandas數據幀中搜索日期時間之前的日期時出現Keyerror

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

我有以下數據框。 我想使用代碼片段中提到的 get_loc ffill 參數獲取最近的日期。 數據框:

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

代碼片段

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)

當我提供日期為 2020-01-02 22:45:00 時,這將返回正確的日期 2020-02-02 22:50:00 但是當我在第一個日期之前給出日期時,我收到一個 keyerror KeyError : Timestamp( '2019-12-20 22:45:00')當我在數據框中的最后一個日期之后給出日期時,我也沒有收到錯誤

我查看了文檔,但找不到為什么我只收到 PRIOR 日期的錯誤。 我希望得到某種 None 對象

文檔

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

在索引中給出一個沒有先前日期時間的日期時間,將導致錯誤,因為它在PREVIOUS索引值中給出最接近的匹配。 由於沒有這樣的索引值,它會拋出一個錯誤。

我相信您正在尋找的是nearest參數,而不是ffill

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM