Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the location index of a given Pandas dataframe index?

In Python Pandas, how do you find the numerical index of a dataframe?

Consider the following example.

import pandas as pd

df = pd.DataFrame(np.arange(20).reshape(5,4), index = np.arange(2,7),columns=["A","B","C","D"])

Output:

    A   B   C   D
2   0   1   2   3
3   4   5   6   7
4   8   9  10  11
5  12  13  14  15
6  16  17  18  19

How do you find the location index of the df.index == 4. The answer should be 2.

like image 431
Hans Avatar asked Nov 25 '25 09:11

Hans


2 Answers

Try .get_loc

In [4]: df.index.get_loc(4)
Out[4]: 2
like image 113
Andy L. Avatar answered Nov 28 '25 00:11

Andy L.


Check get_indexer notice the different here is get_loc will do one value per called , get_indexer you can pass a list

df.index.get_indexer([4])
array([2], dtype=int64)
like image 22
BENY Avatar answered Nov 27 '25 23:11

BENY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!