How to get row number in dataframe in Pandas?

PythonPandas

Python Problem Overview


How can I get the number of the row in a dataframe that contains a certain value in a certain column using Pandas? For example, I have the following dataframe:

     ClientID  LastName
0    34        Johnson
1    67        Smith
2    53        Brows  

How can I find the number of the row that has 'Smith' in 'LastName' column?

Python Solutions


Solution 1 - Python

To get all indices that matches 'Smith'

>>> df[df['LastName'] == 'Smith'].index
Int64Index([1], dtype='int64')

or as a numpy array

>>> df[df['LastName'] == 'Smith'].index.to_numpy()  # .values on older versions
array([1])

or if there is only one and you want the integer, you can subset

>>> df[df['LastName'] == 'Smith'].index[0]
1

You could use the same boolean expressions with .loc, but it is not needed unless you also want to select a certain column, which is redundant when you only want the row number/index.

Solution 2 - Python

df.index[df.LastName == 'Smith']

Or

df.query('LastName == "Smith"').index

Will return all row indices where LastName is Smith

Int64Index([1], dtype='int64')

Solution 3 - Python

df.loc[df.LastName == 'Smith']

will return the row

    ClientID	LastName
1	67	        Smith

and

df.loc[df.LastName == 'Smith'].index

will return the index

Int64Index([1], dtype='int64')

NOTE: Column names 'LastName' and 'Last Name' or even 'lastname' are three unique names. The best practice would be to first check the exact name using df.columns. If you really need to strip the column names of all the white spaces, you can first do

df.columns = [x.strip().replace(' ', '') for x in df.columns]

Solution 4 - Python

 len(df[df["Lastname"]=="Smith"].values)

Solution 5 - Python

count_smiths = (df['LastName'] == 'Smith').sum()

Solution 6 - Python

I know it's many years later but don't try the above solutions without reindexing your dataframe first. As many have pointed out already the number you see to the left of the dataframe 0,1,2 in the initial question is the index INSIDE that dataframe. When you extract a subset of it with a condition you might end up with 0,2 or 2,1, or 2,1 or 2,1,0 depending your condition. So by using that number (called "index") you will not get the position of the row in the subset. You will get the position of that row inside the main dataframe.

use:

np.where([df['LastName'] == 'Smith'])[1][0]

and play with the string 'Smith' to see the various outcomes. Where will return 2 arrays. The 2nd one (index 1) is the one you care about.

NOTE: When the value you search for does not exist where() will return 0 on [1][0]. When is the first value of the list it will also return 0 on [1][0]. Make sure you validate the existence first.

NOTE #2: In case the same value as in your condition is present in the subset multiple times on [1] with will find the list with the position of all occurrences. You can use the length of [1] for future processing if needed.

Solution 7 - Python

You can simply use shape method df[df['LastName'] == 'Smith'].shape

Output
(1,1)

Which indicates 1 row and 1 column. This way you can get the idea of whole datasets

Let me explain the above code DataframeName[DataframeName['Column_name'] == 'Value to match in column']

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsprogissdView Question on Stackoverflow
Solution 1 - PythonjoelostblomView Answer on Stackoverflow
Solution 2 - PythonpiRSquaredView Answer on Stackoverflow
Solution 3 - PythonVaishaliView Answer on Stackoverflow
Solution 4 - PythonVeera SamantulaView Answer on Stackoverflow
Solution 5 - PythonScott BostonView Answer on Stackoverflow
Solution 6 - PythonGabriel CliseruView Answer on Stackoverflow
Solution 7 - PythonrogercakeView Answer on Stackoverflow