Pandas get the row ID based on condition

Viewed 23580

I have the following DataFrame:

Date          best    a    b    c    d
1990-01-01    a       5    4    7    2
1991-01-02    c       10   1    2    0
1992-01-03    d       2    1    4    12
1993-01-04    a       5    8    11   6

I wish to get the row ID where df['Date' == '1992-01-03'].

The expected return is 2.

Any ideas?

2 Answers

To do that, you need to access the DataFrame's index and obtain its id. Following the explanations of https://stackoverflow.com/a/21800319/3921457 and assuming your object is named df you can do something like:

ids = df.index[df['Date'] == '1992-01-03'].tolist()
print(ids)
# [2]

If Date is already the index of the DataFrame, you can change to numeric indexing simply typing: df = df.reset_index().

You can also use np.where:

np.where(df.Date=='1992-01-03')
Related