Pandas stands as one of the most renowned libraries for data manipulation in Python. It offers robust tools for data examination, including the .apply() method, which empowers users to implement a function to each row or column within a DataFrame. Occasionally, you might need to retrieve the index of the row while executing a function.
In this article, we will explore how to obtain the index of a row in a Pandas apply method.
Contents Overview
- Comprehending the Pandas .apply() Method
- Alternative Method Utilizing Lambda Function
- Summary
- Frequently Asked Questions
Comprehending the Pandas .apply() Method
The .apply() method is utilized to invoke a custom function on the rows or columns of a Pandas DataFrame.
- When employed with axis=1, the function is executed row-wise (affecting each row).
- When utilized with axis=0, the function is executed column-wise (affecting each column).
Sample: Retrieving the Index of a Row within Pandas apply() Method
The index of the row can be accessed via the .name property of the row.
Code:
import pandas as pd
df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=['a', 'b', 'c'])
def rowFunc(row):
return row.name
df['Row Index'] = df.apply(rowFunc, axis=1)
print(df)
Result:

Clarification:
- row.name provides the index of the row.
- A new column, ‘d’, has been created, and we have assigned the row indices to it.
Alternative Method Utilizing Lambda Function
A lambda function is an unnamed function in Python that facilitates writing compact, single-line operations. In Pandas, we can combine lambda with methods like apply() to execute modifications either row-wise or column-wise.
Syntax:
df['New_Column'] = df.apply(lambda row: some_operation(row), axis=1)
df['New_Column'] = df.apply(lambda col: some_operation(col), axis=0)
Clarification:
- axis=1 is designated for row-wise operations
- axis=0 is designated for column-wise operations
Example of Acquiring the Index of a Row with Lambda Function
Below is an example that demonstrates obtaining the index of a row using a lambda function:
Code:
Result:

Clarification: In this example, we have added a new column Row_index, and stored the row indices within that column.
Summary
The apply() method is essential for accessing the rows and columns of the DataFrame. By utilizing the .name attribute, we can retrieve the index of a row. Throughout this article, we have explored how to obtain the index of a row in a Pandas apply method.
If you aspire to forge a career in data science, consider exploring our Data Science Course to achieve expertise in the field.
Frequently Asked Questions
The article Retrieving the Index of a Row in a Pandas Apply Method first appeared on Intellipaat Blog.