Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get integer row-index in dataframe where column matches specific value

Given a Pandas dataframe, where one of the columns looks like this:

Date
2016-04-15
2016-04-14
2016-04-13
2016-04-12 
2016-04-11
2016-04-08

How do I get the row-index of a particular value assuming that values are unique?

For example, "2016-04-13" would return 2

like image 885
Ned Hulton Avatar asked May 28 '16 18:05

Ned Hulton


2 Answers

With boolean indexing, you can slice the dataframe to get only the rows where the date equals "2016-04-13" and get the index of the slice:

df[df.Date == "2016-04-13"].index
Out[37]: Int64Index([2], dtype='int64')

With the uniqueness assumption, there will be only one element in that array, so you can take the 0th element:

df[df.Date == "2016-04-13"].index[0]
Out[38]: 2
like image 136
ayhan Avatar answered Oct 15 '22 09:10

ayhan


Use df.index.get_loc('2016-04-14') to get the integer location for requested label. This will return 1 as intital starts from 0. So you can add one to get the index value as 2

like image 39
Tanu Avatar answered Oct 15 '22 09:10

Tanu