4

I have the following dataframe:

     date         value
0    2016-01-01   gfhgh
1    2016-01-02   acgb
2    2016-01-03   yjhgs

I need to get the index of a row where date is a predefined value. For example for 2016-01-02, I need to get 1. Each date will be unique.

0

3 Answers 3

3

Assuming the date field is string:

df[df.date == '<the date value whose index you want>'].index.tolist()

Will return a list of indices whose date is equal to the date value you provided

Sign up to request clarification or add additional context in comments.

Comments

2

IIUC you can use:

print df
        date  value
0 2016-01-01  gfhgh
1 2016-01-02   acgb
2 2016-01-03  yjhgs

print df[df['date'] == pd.to_datetime('2016-01-02')].index.tolist()
[1]

Comments

2

You should be using the index for what it is there for: Accessing data.

Just push the current index into the dataframe, then set the index to the date, and use the .loc to get the number you want.

         date  value
0  2016-01-01  gfhgh
1  2016-01-02   acgb
2  2016-01-03  yjhgs

In [4]: df.reset_index(inplace=True)

In [5]: df.set_index('date', inplace=True)

In [6]: df.loc['2016-01-02','index']
Out[6]: 1

In case you want the whole row, just leave out the , 'index' part

In [7]: df.loc['2016-01-02']
Out[7]: 
index       1
value    acgb
Name: 2016-01-02, dtype: object

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.