Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Let’s see the how to iterate over rows in Pandas Dataframe using
Method #1: Using the
This method iterated over the rows as (index, series) pairs.
Original DataFrame: age name 0 10 Sujeet 1 11 Sameer 2 12 Sumit Rows iterated using iterrows() : Sujeet 10 Sameer 11 Sumit 12
Method #2: Using the
This method returns a named tuple for every row.
getattr() function can be used to get the
row attribute in the returned tuple. This method is faster than Method #1.
Original DataFrame: age name 0 10 Sujeet 1 110 Sameer 2 120 Sumit Rows iterated using itertuples() : Sujeet 10 Sameer 110 Sumit 120
There are few other ways we can iterate over rows in Pandas Dataframe. See Different ways to iterate over rows in Pandas Dataframe.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.