datetime - Get value by date -
i have data frame df:
price 2004-03-19 36.250000 2004-03-20 36.237500 2004-03-21 36.225000 2004-03-22 36.212500 etc... the index of type:
datetimeindex(['2004-03-19', '2004-03-20', '2004-03-21', ...], dtype='datetime64[ns]', length=1691, freq='d') i want retrieve price @ day using df[datetime.date(2004,3,19)]. pandas does:
keyerror: datetime.date(2004, 3, 19)
the following works, can't way supposed work:
df[df.index.isin(pd.datetimeindex([datetime.date(2004,3,19)]))].price.values[0]
the problem here comparison being performed exact match, none of times 00:00:00 no matches occur.
you can use loc datetimeindex:
print df.loc[pd.datetimeindex(['2004-3-19'])] price 2004-03-19 36.25 or can use loc, convert string 2004-3-19 to_datetime , date of datetimeindex:
print df.loc[pd.to_datetime('2004-3-19').date()] price 36.25 name: 2004-03-19 00:00:00, dtype: float64 if need value of price:
print df.loc[pd.datetimeindex(['2004-3-19']), 'price'] 2004-03-19 36.25 name: price, dtype: float64 print df.loc[pd.datetimeindex(['2004-3-19']), 'price'].values[0] 36.25 print df.loc[pd.to_datetime('2004-3-19').date(), 'price'] 36.25 but if add time datetime, datetimeindex match:
print df.loc[pd.to_datetime('2004-3-19 00:00:00')] price 36.25 name: 2004-03-19 00:00:00, dtype: float64 print df.loc[pd.to_datetime('2004-3-19 00:00:00'), 'price'] 36.25
Comments
Post a Comment