Home > Enterprise >  python pandas print specific location of a datetime object
python pandas print specific location of a datetime object

Time:03-09

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

CodePudding user response:

'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

CodePudding user response:

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]
  • Related