3

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?

garciparedes
  • 1,749
  • 2
  • 18
  • 34
wing
  • 43
  • 1
  • 1
  • 5

2 Answers2

8

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().

garciparedes
  • 1,749
  • 2
  • 18
  • 34
  • thanks for your kind advice. Is it possible to return the value in integer data type? – wing Oct 20 '19 at 08:50
  • To do that you can simply access the first element of the list i.e. `ids[0]` (or use `.iloc[0] as described in https://stackoverflow.com/q/24273130/3921457) but you should consider the "not found" case. In any case, it's possible to obtain more than one coincidence, sou maybe you need to implement some kind of logic to pick one of them. – garciparedes Oct 20 '19 at 09:02
3

You can also use np.where:

np.where(df.Date=='1992-01-03')
baccandr
  • 1,090
  • 8
  • 15