How can I iterate through two Pandas columns?

Given a pandas dataframe, we have to iterate through its two columns.
Submitted by Pranit Sharma, on November 23, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Suppose we are given the dataframe with two columns, it is easy to iterate through one column of this dataframe but what if we iterate through the two columns of the Pandas dataframe, if we use two iterators in the for loop it will raise a value error where it would say that there is one more value to unpack.

Also, if we use two iterators and pass both of the columns of the data frame in this for loop, again there will be a value error representing that there are too many values to unpack.

Iterating through two Pandas columns

To iterate through two columns of dataframe we need to use the itertuples() method of dataframe.

Let us understand with the help of an example,

Python program to iterate through two Pandas columns

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating dataframe
df = pd.DataFrame(data=np.random.randint(0,50,(2,2)),columns=list('12'))

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# Iterating through two columns
for a, b in df.itertuples(index=False):
    print("Iterating both columns:\n",a, b)


The output of the above program is:

Example: How can I iterate through two Pandas columns?

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.