Getting the integer index of a Pandas DataFrame row fulfilling a condition?

PythonNumpyPandas

Python Problem Overview


I have the following DataFrame:

   a  b  c
b
2  1  2  3
5  4  5  6

As you can see, column b is used as an index. I want to get the ordinal number of the row fulfilling ('b' == 5), which in this case would be 1.

The column being tested can be either an index column (as with b in this case) or a regular column, e.g. I may want to find the index of the row fulfilling ('c' == 6).

Python Solutions


Solution 1 - Python

Use Index.get_loc instead.

Reusing @unutbu's set up code, you'll achieve the same results.

>>> import pandas as pd
>>> import numpy as np


>>> df = pd.DataFrame(np.arange(1,7).reshape(2,3),
                  columns = list('abc'),
                  index=pd.Series([2,5], name='b'))
>>> df
   a  b  c
b
2  1  2  3
5  4  5  6
>>> df.index.get_loc(5)
1

Solution 2 - Python

You could use np.where like this:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(1,7).reshape(2,3),
                  columns = list('abc'), 
                  index=pd.Series([2,5], name='b'))
print(df)
#    a  b  c
# b         
# 2  1  2  3
# 5  4  5  6
print(np.where(df.index==5)[0])
# [1]
print(np.where(df['c']==6)[0])
# [1]

The value returned is an array since there could be more than one row with a particular index or value in a column.

Solution 3 - Python

With Index.get_loc and general condition:

>>> import pandas as pd
>>> import numpy as np


>>> df = pd.DataFrame(np.arange(1,7).reshape(2,3),
                  columns = list('abc'),
                  index=pd.Series([2,5], name='b'))
>>> df
   a  b  c
b
2  1  2  3
5  4  5  6
>>> df.index.get_loc(df.index[df['b'] == 5][0])
1

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDun PealView Question on Stackoverflow
Solution 1 - Pythonhlin117View Answer on Stackoverflow
Solution 2 - PythonunutbuView Answer on Stackoverflow
Solution 3 - PythonGabriele PiccoView Answer on Stackoverflow