How to Access a Row in a DataFrame in Python

In Python, you can access a row in a DataFrame using various methods provided by the pandas library.

The following examples show how to access a row in a DataFrame in Python.

How to Access a Row by Index

We can use the iloc method to access a row by its index.

Suppose we have the following DataFrame:

import pandas as pd

data = {
    'Date': ['01-03-2023', '01-03-2023', '01-03-2023', '01-03-2023', '02-03-2023', '02-03-2023'],
    'Product_Code': ['A-101', 'A-102', 'A-103', 'B-101', 'B-102', 'B-104'],
    'Product_Name': ['Laptop', 'Mobile', 'Printer', 'Keyboard', 'Scanner', 'Mouse'],
    'Price': [4500, 550, 250, 50, 350, 50],
    'Status': [1, 1, 1, 0, 1, 1]
}

df = pd.DataFrame(data)
print(df)

Output: 👇️

         Date Product_Code Product_Name  Price  Status
0  01-03-2023        A-101       Laptop   4500       1
1  01-03-2023        A-102       Mobile    550       1
2  01-03-2023        A-103      Printer    250       1
3  01-03-2023        B-101     Keyboard     50       0
4  02-03-2023        B-102      Scanner    350       1
5  02-03-2023        B-104        Mouse     50       1

We can use the following code to access the third row:

third_row = df.iloc[2]
print(third_row)

Output: 👇️

Date            01-03-2023
Product_Code         A-103
Product_Name       Printer
Price                  250
Status                   1
Name: 2, dtype: object

In this example, we use the iloc method to access the third row of the DataFrame.

How to Access a Row by Label

We can use the loc method to access a row by its label.

Suppose we have the same DataFrame as above.

We can use the following code to access the row with label “A”:

df = pd.DataFrame({
    'Date': ['01-03-2023', '01-03-2023', '01-03-2023', '01-03-2023', '02-03-2023', '02-03-2023'],
    'Product_Code': ['A-101', 'A-102', 'A-103', 'B-101', 'B-102', 'B-104'],
    'Product_Name': ['Laptop', 'Mobile', 'Printer', 'Keyboard', 'Scanner', 'Mouse'],
    'Price': [4500, 550, 250, 50, 350, 50],
    'Status': [1, 1, 1, 0, 1, 1]
}, index=["A", "B", "C", "D", "E", "F"])

row_by_label = df.loc["A"]
print(row_by_label)

Output: 👇️

Date            01-03-2023
Product_Code         A-101
Product_Name        Laptop
Price                 4500
Status                   1
Name: A, dtype: object

In this example, we use the loc method to access the row with label “A”.