Reputation: 14641
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.
Upvotes: 4
Views: 3910
Reputation: 403
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
Upvotes: 3
Reputation: 32194
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
Upvotes: 2
Reputation: 862396
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]
Upvotes: 2