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:
So, now we will see the application of iterrows() function for obtaining each element of rows.
OUTPUT:
Code 2:
So, now we will apply a iterrow for getting each element of rows in dataframe.
OUTPUT:
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:
So, we will apply iteritems() function for retrieving rows of dataframe.
OUTPUT:
Code 2:
OUTPUT:
So, now we will see the application of iteritems() for retrieving rows from a dataframe.
OUTPUT:
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:
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 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:
So, to learn more about iterations in python for data science, you can check this and this as well.