pythonpandas

How to get the number of the row that contains a specific value in the given column?


I need to get the number of the row that contains a specific value in the given column. It is guaranteed that such value exists in the column and in a unique row.

My attempt:

import pandas as pd
pos = pd.DataFrame(columns=['id', 'pred'])
pos.loc[1,'id'] = [4, 4, 4]
pos.loc[2,'id'] = [2, 3, 3]
pos.loc[3,'id'] = [1, 1, 2]
pos.loc[4,'id'] = [1, 2, 1]

print(pos)

print(pos[pos['id'] == [1, 1, 2]].index[0])

I am getting an error:

ValueError: ('Lengths must match to compare', (6,), (3,))

Solution

  • You need to loop. If you want the position:

    next(i for i, x in enumerate(pos['id']) if [1,1,2] == x)
    

    Output: 2

    Or, to have the index:

    next(i for i, x in zip(pos.index, pos['id']) if [1,1,2] == x)
    

    Output: 3