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,))
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With