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.
Try .get_loc
In [4]: df.index.get_loc(4)
Out[4]: 2
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)
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