Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

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,))
like image 222
Vika Avatar asked Sep 03 '25 17:09

Vika


2 Answers

IIUC, try this:

pos[pos.apply(lambda x: x['id'] == [1,1,2], axis=1)].index[0]

Output:

3

OR

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

Output:

3
like image 145
Scott Boston Avatar answered Sep 05 '25 05:09

Scott Boston


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

like image 36
mozway Avatar answered Sep 05 '25 06:09

mozway