Skip to content
Advertisement

How do I find the position of a value in a pandas.DataFrame?

I want to search for ‘row3’ in the index of the DataFrame below, which should be 2 for a zero-based array.

import numpy as np
import pandas as pd

rownames = ['row1', 'row2', 'row3', 'row4', 'row5']
colnames = ['col1', 'col2', 'col3', 'col4']

# Create a 5 row by 4 column array of integers from 0 to 19
integers = np.arange(20).reshape((5, 4))
table = pd.DataFrame(integers, index=rownames, columns=colnames)

Is there a function which return the row number of ‘row3’? Thanks in advance for any help.

Advertisement

Answer

You could use Index.get_loc (docs):

>>> table.index.get_loc("row3")
2
>>> table.iloc[table.index.get_loc("row3")]
col1     8
col2     9
col3    10
col4    11
Name: row3, dtype: int64
>>> table.loc["row3"]
col1     8
col2     9
col3    10
col4    11
Name: row3, dtype: int64

But this is a somewhat unusual access pattern– never need it myself.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement