Iterating Over Rows and Columns in Pandas:

Iteration is taking each item of something one after the other. Pandas dataframe consists of rows and columns so, for iterating over the dataframe, we iterate a dataframe like a dictionary in Python for Data Science.

In Pandas, we can iterate an element in two ways:

  • Iterate over rows
  • Iterate over columns
Iterating over rows:

For iterating over rows, we use three functions iteritems(), iterrows(), itertuples(). So, these will help in iteration over rows.

Iteration over rows using iterrows():

It is a function which returns each index value along with a series containing data in each row.

Code 1:

Iterating Over Rows and Columns in Pandas Python for Data Science

So, now we will see the application of iterrows() function for obtaining each element of rows.

Iterating Over Rows and Columns in Pandas Python for Data Science

OUTPUT:

Iterating Over Rows and Columns in Pandas Python for Data Science

Code 2:

So, now we will apply a iterrow for getting each element of rows in dataframe.

OUTPUT:

Iterating Over Rows and Columns in Pandas Python for Data Science

Iterating over rows using iteritems():

For iterating over rows, we use the iteritems() function. It is a function which iterates over each column as key, value pair with label as key and the column value as series object.

Code 1:

Iterating Over Rows and Columns in Pandas Python for Data Science

So, we will apply iteritems() function for retrieving rows of dataframe.

OUTPUT:

Code 2:

Iterating Over Rows and Columns in Pandas Python for Data Science

OUTPUT:

So, now we will see the application of iteritems() for retrieving rows from a  dataframe.

OUTPUT:

Iterating Over Rows and Columns in Pandas Python for Data Science

Iterating over rows using itertuples():

It is a function which returns a tuple for each row in the dataframe. So, the first element of tuple will be the row’s corresponding index value and the remaining values are the row values.

Code 1:

Iterating Over Rows and Columns in Pandas Python for Data Science

So, now we will apply itertuples() function to get tuple for each row.

OUTPUT:

Code 2:

So, now we will see application of itertuples() for getting tuple of each rows.

OUTPUT:

Iterating Over Rows and Columns in Pandas Python for Data Science

Iterating over columns:

For iterating over columns we should create a list of dataframe columns. So, we will iterate through that list for pulling out the dataframe columns.

Code 1:

OUTPUT:

Code 2:


OUTPUT:

Iterating Over Rows and Columns in Pandas Python for Data Science

So, to learn more about iterations in python for data science, you can check this and this as well.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.