In this article we will different ways to iterate over all or certain columns of a Dataframe.

Let’s first create a Dataframe i.e.

Contents of created dataframe empDfObj  are,

Iterate over columns of a DataFrame using DataFrame.iteritems()

Dataframe class provides a member function iteritems() i.e.

DataFrame.iteritems()

It yields an iterator which can can be used to iterate over all the columns of a dataframe. For each column in the Dataframe it returns an iterator to the tuple containing the column name and column contents as series.

Let’s user iteritems() to iterate over the columns of above created Dataframe,

Output:

As there were 3 columns so 3 tuples were returned during iteration.

Iterate over columns in dataframe using Column Names

Dataframe.columns returns a sequence of column names. We can iterate over these column names and for each column name we can select the column contents by column name i.e.

Output:

Iterate over certain columns in dataframe

Suppose we want to iterate over two columns i.e. Name & Age in the above created dataframe. To do the we can select those columns only from dataframe and then iterate over them i.e.

Output:

Iterate Over columns in dataframe in reverse order

As Dataframe.columns returns a sequence of column names. We can reverse iterate over these column names and for each column name we can select the column contents by column name i.e.

Output:

It basically printed the all the columns of Dataframe in reverse order.

Iterate Over columns in dataframe by index using iloc[]

To iterate over the columns of a Dataframe by index we can iterate over a range i.e. 0 to Max number of columns then for each index we can select the columns contents using iloc[]. Let’s see how to iterate over all columns of dataframe from 0th index to last index i.e.

Output:

Complete example is as follows,

Output:

 

 

Click Here to Subscribe for more Articles / Tutorials like this.