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.

Iterating through two Pandas columns

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.

Hence, 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 code 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)

Output:

Example: How can I iterate through two Pandas columns?

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.