How to get the index value in a dataframe by comparing date with a datetime object in that dataframe?

Viewed 1071

I have a dataframe like the following. I would like to get the index value by checking the date. For example if the date is 2018-04-05, I need to get the index value as 3. Can someone let me know how to do that?

       close                      date     high      low     open   volume
0    1536.95 2018-04-02 09:15:00+05:30  1545.00  1509.40  1509.40   420761   
1    1554.80 2018-04-03 09:15:00+05:30  1562.00  1534.00  1534.00   201412   
2    1530.00 2018-04-04 09:15:00+05:30  1576.85  1525.85  1554.00   171614   
3    1552.35 2018-04-05 09:15:00+05:30  1559.70  1536.90  1551.40   198303   
4    1553.25 2018-04-06 09:15:00+05:30  1560.95  1542.85  1558.00   119196   
5    1541.30 2018-04-09 09:15:00+05:30  1559.15  1535.65  1552.90   175732   
6    1539.15 2018-04-10 09:15:00+05:30  1555.90  1531.45  1555.90   112086   
7    1533.55 2018-04-11 09:15:00+05:30  1543.50  1520.10  1531.90   319761   
3 Answers

You can use the normalize attribute of datetime to zero-out the time part, which will then allow you to directly compare the datetime with the string

import pandas as pd
date= '2018-04-05'
#df['date'] = pd.to_datetime(df.date)

df[df.date.dt.normalize() == date].index.values
#array([3], dtype=int64)

You can also do the following:

a = [1,2,3,4,5]
b = [1,0.4,0.3,0.5,0.2]

df = pd.DataFrame({'a':a , 'b': b})

df.loc[df['a'] == 1].index.item()

The output being:

df is:

    a    b
0  1  1.0
1  2  0.4
2  3  0.3
3  4  0.5
4  5  0.2


index:
 0

The way I'd do it is

df.loc[df["date"] == "2018-04-05"].index[0]
# outputs
(3, 1552.3499999999999)

or

df.loc[df["date"] == "2018-04-05"].index.values
# outputs
array([(3, 1552.35)], dtype=object)

In both cases you can select 1st element

df.loc[df["close"] == "2018-04-05"].index[0][0] #gives 3

df.loc[df["close"] == "2018-04-05"].index.values[0][0] #gives 3

Related