iterate over pandas dataframe rows

How to Iterate Over Rows in Pandas Dataframe

Python Pandas is a powerful library to process data. Often you may need to iterate over rows in Pandas Dataframe. In this article, we will learn a couple of different ways to iterate over rows in Pandas DataFrame.

How to Iterate Over Rows in Pandas DataFrame

Let us say you have the following dataframe in python pandas.

import pandas as pd
inp = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}]
df = pd.DataFrame(inp)
print df

Here is the output you will see.

   c1   c2
0  10  100
1  11  110
2  12  120

Let us say you want to iterate over the rows one by one and display their contents.

First, we will reset the index since we want to start from the first row.

df = df.reset_index()  # make sure indexes pair with number of rows

Next, we will use dataframe.iterrows() to iterate through the rows of dataframe.

for index, row in df.iterrows():
    print(row['c1'], row['c2'])

In the above loop, we directly print each row’s column values by using the column names. Here is the output you will see.

10 100
11 110
12 120

In this article, we have learnt how to iterate over rows in Pandas in Python.

Also read:

How to Get Row Count of Pandas DataFrame
How to Merge DataFrames in Pandas Based on Columns
How to Change Default Display Manager in Ubuntu
How to Fix “Please Install All Available Updates Before Upgrade”
How to Change Login Screen Background in Ubuntu

Leave a Reply

Your email address will not be published.