Home > other >  Pandas : How to get the postition (number of row) of a value
Pandas : How to get the postition (number of row) of a value

Time:07-06

I have my pandas dataframe and i need to find the index of a certain value. But the thing is, this df does from an other one where i had to cut some part using the df.loc, so it ends up like :

index value
1448  31776
1449  32088
1450  32400
1451  32712
1452  33024

Let's say i need to find the index of the value '32400', with the function df.index[df.value == 32400] i get 1450, but what I want is 2.

Would you know how i could get this value?

CodePudding user response:

First idea is create default index starting by 0 by DataFrame.reset_index with drop=True:

df = df.reset_index(drop=True)
idx = df.index[df.value == 32400]
print (idx)
Int64Index([2], dtype='int64')

Or use numpy - e.g. by numpy.where with condition for positions of match:

idx = np.where(df.value == 32400)[0]
print (idx)
[2]

Or use numpy.argmax - it working well if match at least one value:

idx = np.argmax(df.value == 32400)
print (idx)
2

idx = np.argmax(df.value == 10)
print (idx)
0
  • Related