0

I have looked at other solutions online but none of them work on my dataframe. I want to get the exact location of a specific datetime object but this code produces this keyerror KeyError: '2018-1-31'

import pandas as pd    
data=pd.DataFrame()
dti = pd.date_range("2018-01-01", periods=10, freq="M")
data['dti']=dti
print((data['dti'].loc['2018-1-31'])) # it should print 0 since this date is in the first row
BigBen
  • 46,229
  • 7
  • 24
  • 40

2 Answers2

0

'dti' is not the index, so you cannot use loc directly. You need to generate a boolean Series first:

data.loc[data['dti'].eq('2018-1-31'), 'dti']

output:

0   2018-01-31
Name: dti, dtype: datetime64[ns]

to get the index:

data.loc[data['dti'].eq('2018-1-31'), 'dti'].index
mozway
  • 194,879
  • 13
  • 39
  • 75
  • thanks, and how do you print all locations between two dates ? – jack johnjacks Mar 09 '22 at 14:01
  • depends on the data (sorted or not, duplicates or not). Can you provide an example in your question (input and output)? – mozway Mar 09 '22 at 14:02
  • i added these lines to the code above to calculate the mean of another column between two dates : data['nr']=range(10) print(data) print(data.loc[(data['dti'] >= (2018-1-31) & df['timestamp'] <= (2018, 4, 30)), 'nr'].mean()) and it generates a typeerror. – jack johnjacks Mar 09 '22 at 14:08
0

You could try following to get index (see answer):

data[data['dti']=='2018-01-31'].index[0]

Output is:

0

And if you want indices for the range, you could using & for the condition to filter, may be something like below:

data[(data['dti']>'2018-2-28') & (data['dti']<'2018-6-30')].index.tolist()

Output is:

[2, 3, 4]
niraj
  • 17,498
  • 4
  • 33
  • 48