In Pandas, What Is The Method To Iterate Over Rows In A DataFrame Using Python?

To iterate over rows in a DataFrame in Pandas, you can use the iterrows() method. Here’s an example:

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['John', 'Jane', 'Steve'],
        'Age': [28, 31, 35],
        'Country': ['USA', 'Canada', 'UK']}

df = pd.DataFrame(data)

# Iterate over rows using iterrows()
for index, row in df.iterrows():
    print('Index:', index)
    print('Name:', row['Name'])
    print('Age:', row['Age'])
    print('Country:', row['Country'])
    print()

Output:

Index: 0
Name: John
Age: 28
Country: USA

Index: 1
Name: Jane
Age: 31
Country: Canada

Index: 2
Name: Steve
Age: 35
Country: UK

In the above example, we first import the pandas library and create a sample DataFrame. Then we iterate over the rows using the iterrows() method. Inside the loop, we can access the index and values of each row using index and row variables, respectively. In this example, we print the index, Name, Age, and Country of each row.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!