close

How to get row number in dataframe in Pandas?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to get row number in dataframe in Pandas in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to get row number in dataframe in Pandas?

  1. How to get row number in dataframe in Pandas?

    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.

  2. get row number in dataframe in Pandas

    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.

Method 1

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.

Method 2

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

Or

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

Will return all row indices where LastName is Smith

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

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read